id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,540,749
|
traits_util.h
|
nitnelave_lru_cache/lru_cache/traits_util.h
|
#ifndef LRU_CACHE_TRAITS_UTIL_H_
#define LRU_CACHE_TRAITS_UTIL_H_
#include <limits>
#include <tuple>
#include <type_traits>
namespace lru_cache::internal {
template <typename F>
struct function_info : public function_info<decltype(&F::operator())> {};
template <typename ReturnType, typename... Args>
struct function_info<ReturnType (*)(Args...)> {
using return_type = ReturnType;
using args_type = std::tuple<Args...>;
};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_info<ReturnType (ClassType::*)(Args...) const> {
using return_type = ReturnType;
using args_type = std::tuple<Args...>;
};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_info<ReturnType (ClassType::*)(Args...)> {
using return_type = ReturnType;
using args_type = std::tuple<Args...>;
};
template <typename F>
using return_t = typename function_info<F>::return_type;
template <typename F>
using args_t = typename function_info<F>::args_type;
// Resolves to the unqualified type of the only argument of F, or void
// otherwise.
template <typename F>
using single_arg_t =
std::conditional_t<std::tuple_size_v<args_t<F>> == 1,
std::remove_cv_t<std::remove_reference_t<
std::tuple_element_t<0, args_t<F>>>>,
void>;
template <size_t N, typename T>
static constexpr size_t is_representable =
N <= static_cast<size_t>(std::numeric_limits<T>::max());
template <size_t N>
using index_type_for = std::conditional_t<
is_representable<N, uint8_t>, uint8_t,
std::conditional_t<
is_representable<N, uint16_t>, uint16_t,
std::conditional_t<is_representable<N, uint32_t>, uint32_t, uint64_t>>>;
} // namespace lru_cache::internal
#endif // LRU_CACHE_TRAITS_UTIL_H_
| 1,825
|
C++
|
.h
| 46
| 35.869565
| 80
| 0.691568
|
nitnelave/lru_cache
| 33
| 12
| 1
|
MPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,750
|
lru_cache.h
|
nitnelave_lru_cache/lru_cache/lru_cache.h
|
#ifndef LRU_CACHE_LRU_CACHE_H_
#define LRU_CACHE_LRU_CACHE_H_
#include "dynamic_lru_cache.h"
#include "node_lru_cache.h"
#include "static_lru_cache.h"
namespace lru_cache
{
// Create simple cache
template <typename Key, typename Value>
NodeLruCache<Key, Value>
make_cache(
size_t max_size) {
return {max_size};
}
// Memoize a single-argument function.
template <typename ValueProvider>
NodeLruCache<internal::single_arg_t<ValueProvider>,
internal::return_t<ValueProvider>, ValueProvider>
memoize_function(
size_t max_size, ValueProvider v) {
return {max_size, v};
}
}
#endif // LRU_CACHE_LRU_CACHE_H_
| 632
|
C++
|
.h
| 24
| 24.083333
| 62
| 0.747927
|
nitnelave/lru_cache
| 33
| 12
| 1
|
MPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,751
|
lru_cache_impl.h
|
nitnelave_lru_cache/lru_cache/lru_cache_impl.h
|
// Internal implementation of an LRU cache.
//
// This base class can be re-used to provide the logic of an LRU cache with
// different underlying containers.
//
// The cache is based on a 2-container approach:
// - a map of key -> IndexType.
// - a linked list of Node, indexable by IndexType.
//
// The map allows for fast lookups, while the linked list keeps track of the
// order of access (or insertion) of the items.
//
// User-provided functions are called to fetch a new value, and (optionally)
// when a value is dropped.
//
// In addition to cached lookups, this cache provides iteration on all the
// elements in the cache in the access order.
//
// ADD AN IMPLEMENTATION
//
// In order to use this class, several constraints must be satisfied:
// - LruCacheImpl uses the CRTP pattern, so the implementation must
// publicly inherit from LruCacheImpl.
// - The choice of containers is up to the implementation. It must provide
// types (or wrappers) that conform to the limited implementation of the
// Map and NodeContainer (see below).
//
// Required implementation interface:
// - You probably want to declare the LruCacheImpl a friend class to make the
// rest of the interface private.
//
// size_t max_size() const;
// NodeContainer &node_container();
// Map &map();
// const Map &map() const;
// IndexType index_of(const Key &key) const;
//
// Required Map interface:
// size_t size() const;
// bool empty() const;
// void emplace(const Key &key, IndexType index);
// void erase(const Key &key);
//
// Required NodeContainer interface:
// // INVALID_INDEX must be a valid value of IndexType. When the index is an
// // integer, a common way to go is to reserve the max value to be invalid,
// // although it reduces the max number of indexable values by 1.
// static constexpr IndexType INVALID_INDEX = ...;
// using node_type = internal::Node<Key, Value, IndexType>;
//
// node_type &operator[](IndexType index);
// const node_type &operator[](IndexType index) const;
//
// // Add the node at the back. This is called while the container
// // is not full yet, so no replacement occurs.
// IndexType emplace_back(node_type node);
//
// // Replace the entry at the given index with the given key with the new
// // node. This implies that the container is full.
// IndexType replace_entry(IndexType index, const Key &old_key,
// node_type new_node);
//
// Required CacheOptions interface:
// using IndexType = ...;
// using Node = internal::Node<Key, Value, IndexType>;
// using Map = ...; // map of key -> IndexType
// using NodeContainer = ...;
// // Whether to sort the element by access order or insertion order.
// static constexpr bool ByAccessOrder = ...;
#ifndef LRU_CACHE_LRU_CACHE_IMPL_H_
#define LRU_CACHE_LRU_CACHE_IMPL_H_
#include <cassert>
#include <functional>
#include <iterator>
#include <type_traits>
#include "default_providers.h"
#include "traits_util.h"
namespace lru_cache::internal {
// Tag to tell Node to use a Node* as linked list element.
struct self_ptr_link_tag {};
// Element in the linked list of last accessed.
template <typename Key, typename Value, typename index_type>
struct Node {
// To allow pointer-style linked list, if index_type is self_ptr_link_tag we
// use Node* as index type.
using IndexType =
std::conditional_t<std::is_same_v<index_type, self_ptr_link_tag>, Node*,
index_type>;
using key_type = Key;
using value_type = Value;
using pair_type = std::pair<Key, Value>;
Node() = default;
Node(Key key, Value value, IndexType prev, IndexType next)
: prev_(prev),
next_(next),
value_pair_(std::move(key), std::move(value)) {}
// Move-only node.
Node(const Node&) = delete;
Node& operator=(const Node&) = delete;
Node(Node&&) = default;
Node& operator=(Node&&) = default;
Value& value() { return value_pair().second; }
const Value& value() const { return value_pair().second; }
Key& key() { return value_pair().first; }
const Key& key() const { return value_pair().first; }
pair_type& value_pair() { return value_pair_; }
const pair_type& value_pair() const { return value_pair_; }
// The hash of a node is just the hash of the key.
template <typename H>
friend H AbslHashValue(H h, const Node& n) {
return H::combine(std::move(h), n.key());
}
// Link to the next newer element.
IndexType prev_;
// Link to the next older element.
IndexType next_;
private:
// The content of the key and value.
pair_type value_pair_;
};
// The linked list keeping track of the access order.
template <typename Key, typename Value, typename IndexType,
typename NodeContainer>
struct LinkedList {
using node_type = typename NodeContainer::node_type;
static constexpr IndexType INVALID_INDEX = NodeContainer::INVALID_INDEX;
LinkedList(NodeContainer& nodes) : list_content_(nodes) {}
// The element that was access the longest ago.
node_type& oldest() {
assert(oldest_ != INVALID_INDEX);
return list_content_[oldest_];
}
IndexType oldest_index() const { return oldest_; }
// The element that was last access.
node_type& latest() {
assert(latest_ != INVALID_INDEX);
return list_content_[latest_];
}
// Add a new element to the list.
// This assumes that the list (and the underlying container) is not full.
std::pair<std::reference_wrapper<Value>, IndexType> emplace_latest(
Key key, Value value, size_t curent_size) {
IndexType new_index = list_content_.emplace_back(
node_type{std::move(key), std::move(value), INVALID_INDEX, latest_});
if (oldest_ == INVALID_INDEX) {
oldest_ = new_index;
} else {
latest().prev_ = new_index;
}
latest_ = new_index;
return {latest().value(), new_index};
}
// Move the element to the front of the queue.
// This doesn't move anything in memory, it just changes the pointers around.
void move_to_front(IndexType index) {
if (index == latest_) return;
node_type& node = list_content_[index];
// It's not the first, so it has a prev.
assert(node.prev_ != INVALID_INDEX);
node_type& prev_node = list_content_[node.prev_];
prev_node.next_ = node.next_;
if (node.next_ != INVALID_INDEX) {
list_content_[node.next_].prev_ = node.prev_;
} else {
oldest_ = node.prev_;
}
node.next_ = latest_;
list_content_[latest_].prev_ = index;
node.prev_ = INVALID_INDEX;
latest_ = index;
}
// Replace the oldest entry, with key old_key, with the new value and the new
// key.
// Depending on the container implementation, that can either re-use the
// memory or delete and create a new one.
const Value& replace_oldest_entry(const Key& old_key, const Key& new_key,
Value new_value) {
node_type& oldest_node = oldest();
node_type& one_before_last = list_content_[oldest_node.prev_];
oldest_ = oldest_node.prev_;
IndexType oldest_node_index = one_before_last.next_;
auto new_index = list_content_.replace_entry(
oldest_node_index, old_key,
node_type{new_key, std::move(new_value), INVALID_INDEX, latest_});
latest().prev_ = new_index;
one_before_last.next_ = INVALID_INDEX;
latest_ = new_index;
return list_content_[new_index].value();
}
node_type& operator[](IndexType index) { return list_content_[index]; }
const node_type& operator[](IndexType index) const {
return list_content_[index];
}
NodeContainer& list_content_;
// Last element accessed.
IndexType latest_ = INVALID_INDEX;
// Oldest element accessed.
IndexType oldest_ = INVALID_INDEX;
};
// Main cache implementation base.
template <
// The class that inherits from this. See
// https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern.
typename CRTPBase,
// Type of the user key.
typename Key,
// Type of the user value.
typename Value,
// The struct defining the options for the cache.
typename CacheOptions,
// Type of the function that fetches a new value given the key. If
// the function type is impossible to write (e.g. lambda) this can be
// replaced by std::function, but at a performance cost.
typename ValueProvider = decltype(&throwing_value_producer<Key, Value>),
// The type of the function called when a value is dropped.
typename DroppedEntryCallback =
decltype(&no_op_dropped_entry_callback<Key, Value>)>
class LruCacheImpl {
public:
// For easy access in the derived classes.
using Impl = LruCacheImpl;
using IndexType = typename CacheOptions::IndexType;
using Map = typename CacheOptions::Map;
using NodeContainer = typename CacheOptions::NodeContainer;
static constexpr bool ByAccessOrder = CacheOptions::ByAccessOrder;
using node_type = typename NodeContainer::node_type;
using value_type = typename node_type::pair_type;
using linked_list = LinkedList<Key, Value, IndexType, NodeContainer>;
static constexpr IndexType INVALID_INDEX = linked_list::INVALID_INDEX;
LruCacheImpl(
ValueProvider value_provider = throwing_value_producer<Key, Value>,
DroppedEntryCallback dropped_entry_callback =
no_op_dropped_entry_callback<Key, Value>)
: value_list_(node_container()),
value_provider_(std::move(value_provider)),
dropped_entry_callback_(std::move(dropped_entry_callback)) {}
// The number of elements in the cache.
size_t size() const { return map().size(); }
bool empty() const { return map().empty(); }
// Whether the key is in the cache.
bool contains(const Key& key) const { return index_of(key) != INVALID_INDEX; }
// Get the value for the given key. If the key is not in the cache, the value
// provider will be called to get the value, and it will be added to the
// cache. That might cause the LRU entry to be dropped.
const Value& operator[](const Key& key) { return get(key); }
const Value& operator()(const Key& key) { return get(key); }
const Value& get(const Key& key) {
const Value* value_or_null = get_or_null(key);
if (value_or_null != nullptr) return *value_or_null;
// Fetch the value.
Value new_value = value_provider_(key);
return insert(key, std::move(new_value));
}
const Value* get_or_null(const Key& key) {
IndexType index = index_of(key);
if (index == INVALID_INDEX) {
return nullptr;
}
node_type& node = value_list_[index];
if constexpr (ByAccessOrder) {
// Update the last access order.
value_list_.move_to_front(index);
}
return &node.value();
}
const Value& insert(const Key& key, Value new_value) {
if (max_size() == size()) {
// Cache is full, drop the last entry and replace it.
return replace_oldest_entry(key, std::move(new_value));
}
// Append at the back of the cache.
size_t current_size = size();
const auto& [value, new_index] =
value_list_.emplace_latest(key, std::move(new_value), current_size);
map().emplace(key, new_index);
return value;
}
private:
// Replace the oldest entry with the new entry key/new_value.
const Value& replace_oldest_entry(const Key& key, Value new_value) {
node_type& oldest_node = value_list_.oldest();
Key old_key = oldest_node.key();
map().erase(oldest_node.key());
dropped_entry_callback_(std::move(oldest_node.key()),
std::move(oldest_node.value()));
map().emplace(key, value_list_.oldest_index());
return value_list_.replace_oldest_entry(old_key, key, std::move(new_value));
}
// The specific implementation subclass.
CRTPBase& base() { return *static_cast<CRTPBase*>(this); }
const CRTPBase& base() const { return *static_cast<const CRTPBase*>(this); }
size_t max_size() const { return base().max_size(); }
NodeContainer& node_container() { return base().node_container(); }
Map& map() { return base().map(); }
const Map& map() const { return base().map(); }
IndexType index_of(const Key& key) const { return base().index_of(key); }
public:
// Iterator, to go through the entries in access/insertion order (potentially
// reversed).
template <typename IteratorValueType, bool Reversed>
class Iterator {
public:
using difference_type = std::ptrdiff_t;
using value_type = IteratorValueType;
using pointer = IteratorValueType*;
using reference = IteratorValueType&;
using iterator_category = std::bidirectional_iterator_tag;
Iterator() = default;
Iterator(const linked_list& list, IndexType index)
: linked_list_(&list), current_index_(index) {}
IteratorValueType& operator*() { return node().value_pair(); }
Iterator& operator++() {
to_next();
return *this;
}
Iterator operator++(int) {
Iterator tmp = *this;
++*this;
return tmp;
}
Iterator& operator--() {
to_prev();
return *this;
}
Iterator operator--(int) {
Iterator tmp = *this;
--*this;
return tmp;
}
bool operator==(const Iterator& other) const {
if (other.current_index_ == INVALID_INDEX &&
current_index_ == INVALID_INDEX) {
return true;
}
return other.linked_list_ == linked_list_ &&
other.current_index_ == current_index_;
}
bool operator!=(const Iterator& other) const { return !(*this == other); }
private:
void to_next() {
if constexpr (Reversed) {
current_index_ = node().prev_;
} else {
current_index_ = node().next_;
}
}
void to_prev() {
if constexpr (Reversed) {
current_index_ = node().next_;
} else {
current_index_ = node().prev_;
}
}
const node_type& node() const {
assert(current_index_ != INVALID_INDEX);
return (*linked_list_)[current_index_];
}
const linked_list* linked_list_;
IndexType current_index_;
};
using iterator = Iterator<value_type, false>;
using const_iterator = Iterator<const value_type, false>;
using reversed_iterator = Iterator<value_type, true>;
using const_reversed_iterator = Iterator<const value_type, true>;
iterator begin() {
if (size() == 0) return {value_list_, INVALID_INDEX};
return {value_list_, value_list_.latest_};
}
iterator end() { return {value_list_, INVALID_INDEX}; }
const_iterator begin() const {
if (size() == 0) return {value_list_, INVALID_INDEX};
return {value_list_, value_list_.latest_};
}
const_iterator end() const { return {value_list_, INVALID_INDEX}; }
reversed_iterator rbegin() {
if (size() == 0) return {value_list_, INVALID_INDEX};
return {value_list_, value_list_.oldest_};
}
reversed_iterator rend() { return {value_list_, INVALID_INDEX}; }
const_reversed_iterator rbegin() const {
if (size() == 0) return {value_list_, INVALID_INDEX};
return {value_list_, value_list_.oldest_};
}
const_reversed_iterator rend() const { return {value_list_, INVALID_INDEX}; }
// Find an element in the cache.
template <typename K>
iterator find(const K& key) {
IndexType index = index_of(key);
return {value_list_, index};
}
template <typename K>
const_iterator find(const K& key) const {
IndexType index = index_of(key);
return {value_list_, index};
}
private:
linked_list value_list_;
ValueProvider value_provider_;
DroppedEntryCallback dropped_entry_callback_;
};
} // namespace lru_cache::internal
namespace std {
// The hash of a node is just the hash of the key.
template <typename Key, typename Value, typename IndexType>
struct hash<lru_cache::internal::Node<Key, Value, IndexType>> {
std::size_t operator()(
const lru_cache::internal::Node<Key, Value, IndexType>& node) const {
return hash<Key>()(node.key());
}
};
} // namespace std
#endif // LRU_CACHE_LRU_CACHE_IMPL_H_
| 15,966
|
C++
|
.h
| 412
| 34.63835
| 80
| 0.676467
|
nitnelave/lru_cache
| 33
| 12
| 1
|
MPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,752
|
node_lru_cache.h
|
nitnelave_lru_cache/lru_cache/node_lru_cache.h
|
// LRU cache based on absl::node_hash_set.
//
// This takes advantage of the fact that the nodes are pointer-stable in a
// node_hash_set to encode the linked list directly inside the values. That way
// there is no need to keep a vector alongside the map, so there is less
// information duplication.
//
// This is supposed to mirror the way LinkedHashMap works in Java.
#ifndef LRU_CACHE_NODE_LRU_CACHE_H_
#define LRU_CACHE_NODE_LRU_CACHE_H_
#include <vector>
#include "absl/container/node_hash_set.h"
#include "lru_cache_impl.h"
#include "traits_util.h"
namespace lru_cache {
// Adaptor over the node_hash_set to provide the linked_list.
template <typename Node, typename Map>
struct MapNodeContainer {
using node_type = Node;
using key_type = typename node_type::key_type;
using IndexType = typename Node::IndexType; // Node*
static constexpr IndexType INVALID_INDEX = nullptr;
MapNodeContainer(Map& map) : map_(map) {}
IndexType emplace_back(node_type node) {
auto [it, inserted] = map_.emplace_node(std::move(node));
assert(inserted);
return node_to_index(*it);
}
IndexType replace_entry(IndexType index, const key_type& old_key,
node_type new_node) {
map_.erase_node(old_key);
return emplace_back(std::move(new_node));
}
node_type& operator[](IndexType index) { return index_to_node(index); }
const node_type& operator[](IndexType index) const {
return index_to_node(index);
}
private:
IndexType node_to_index(const Node& node) const {
// Unfortunate, but necessary.
return const_cast<IndexType>(&node);
}
Node& index_to_node(IndexType ptr) const { return *ptr; }
Map& map_;
};
// Adaptor over a node_hash_set to provide the appearance of a map of Key ->
// Node*.
// The set contains Nodes.
template <typename Key, typename Value, typename Node>
struct MapAdaptor {
// We want to allow heterogeneous lookup to be able to lookup a key in the
// set, as if it was a map.
struct NodeComparator {
// absl heterogeneous marker.
using is_transparent = void;
bool operator()(const Node& n1, const Node& n2) const {
return n1.key() == n2.key();
}
bool operator()(const Key& k, const Node& n) const { return k == n.key(); }
bool operator()(const Node& n, const Key& k) const { return k == n.key(); }
};
// The hash of a node is just the hash of the key.
struct TransparentHasher
: public absl::container_internal::hash_default_hash<Key> {
using is_transparent = void;
size_t operator()(const Key& value) const {
return absl::container_internal::hash_default_hash<Key>::operator()(
value);
}
size_t operator()(const Node& value) const {
return operator()(value.key());
}
};
using IndexType = typename Node::IndexType; // Node*
using Set = absl::node_hash_set<Node, TransparentHasher, NodeComparator>;
static_assert(
absl::container_internal::IsTransparent<typename Set::hasher>::value,
"Hasher is not transparent, heterogeneous lookup won't work");
static_assert(
absl::container_internal::IsTransparent<typename Set::key_equal>::value,
"Comparator is not transparent, heterogeneous lookup won't work");
size_t size() const { return set_.size(); }
bool empty() const { return set_.empty(); }
using const_iterator = typename Set::const_iterator;
const_iterator find(const Key& key) const { return set_.find(key); }
const_iterator end() const { return set_.end(); }
void emplace(const Key& key, IndexType index) {
// Do nothing, the emplace is in the node container.
}
void erase(const Key& key) {
// Do nothing, the node will be erased at the right moment by the node
// container calling erase_node.
}
std::pair<typename Set::iterator, bool> emplace_node(Node node) {
// Called by the node container.
return set_.emplace(std::move(node));
}
void erase_node(const Key& key) { set_.erase(key); }
private:
Set set_;
};
// Set of options for the set-based LRU cache.
template <typename Key, typename Value, bool by_access_order = true>
struct NodeLruCacheOptions {
using Node = internal::Node<Key, Value, internal::self_ptr_link_tag>;
using IndexType = Node*;
static_assert(std::is_same_v<IndexType, typename Node::IndexType>);
using Map = MapAdaptor<Key, Value, Node>;
using NodeContainer = MapNodeContainer<Node, Map>;
static constexpr bool ByAccessOrder = by_access_order;
};
// Set-based LRU cache, with the linked list baked in the values.
template <typename Key, typename Value,
typename ValueProvider =
decltype(&internal::throwing_value_producer<Key, Value>),
typename DroppedEntryCallback = void (*)(Key, Value)>
class NodeLruCache
: public internal::LruCacheImpl<
NodeLruCache<Key, Value, ValueProvider, DroppedEntryCallback>, Key,
Value, NodeLruCacheOptions<Key, Value>, ValueProvider,
DroppedEntryCallback> {
using Base = typename NodeLruCache::Impl;
friend Base;
using options_type = NodeLruCacheOptions<Key, Value>;
using IndexType = typename options_type::IndexType;
using NodeContainer = typename options_type::NodeContainer;
using Map = typename options_type::Map;
using Node = typename options_type::Node;
public:
NodeLruCache(size_t max_size,
ValueProvider value_provider =
internal::throwing_value_producer<Key, Value>,
DroppedEntryCallback dropped_entry_callback =
internal::no_op_dropped_entry_callback<Key, Value>)
: Base(std::move(value_provider), std::move(dropped_entry_callback)),
max_size_(max_size),
nodes_(map_) {}
size_t max_size() const { return max_size_; }
protected:
NodeContainer& node_container() { return nodes_; }
Map& map() { return map_; }
const Map& map() const { return map_; }
IndexType index_of(const Key& key) const {
auto it = map_.find(key);
if (it != map_.end()) {
return const_cast<Node*>(&*it);
}
return NodeContainer::INVALID_INDEX;
}
private:
const size_t max_size_;
Map map_;
NodeContainer nodes_;
};
// Factory for the set-based LRU cache.
template <typename Key, typename Value,
typename ValueProvider =
decltype(&internal::throwing_value_producer<Key, Value>),
typename DroppedEntryCallback = void (*)(Key, Value)>
NodeLruCache<Key, Value, ValueProvider, DroppedEntryCallback>
make_node_lru_cache(
size_t max_size,
ValueProvider v = internal::throwing_value_producer<Key, Value>,
DroppedEntryCallback c =
internal::no_op_dropped_entry_callback<Key, Value>) {
return {max_size, v, c};
}
// Same as above, deducing Key and Value from the single-argument function
// ValueProvider.
template <typename ValueProvider,
typename DroppedEntryCallback = decltype(
&internal::no_op_dropped_entry_callback_deduced<ValueProvider>)>
NodeLruCache<internal::single_arg_t<ValueProvider>,
internal::return_t<ValueProvider>, ValueProvider,
DroppedEntryCallback>
make_node_lru_cache_deduced(
size_t max_size, ValueProvider v,
DroppedEntryCallback c =
internal::no_op_dropped_entry_callback_deduced<ValueProvider>) {
return {max_size, v, c};
}
} // namespace lru_cache
#endif // LRU_CACHE_NODE_LRU_CACHE_H_
| 7,389
|
C++
|
.h
| 183
| 35.84153
| 79
| 0.698495
|
nitnelave/lru_cache
| 33
| 12
| 1
|
MPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,753
|
exception.h
|
nitnelave_lru_cache/lru_cache/exception.h
|
#ifndef LRU_CACHE_EXCEPTION_H_
#define LRU_CACHE_EXCEPTION_H_
#include <exception>
#include <iostream>
#include <sstream>
#include <type_traits>
namespace lru_cache {
namespace internal {
template <typename, typename = void>
struct is_printable : std::false_type {};
template <typename T>
struct is_printable<T, std::void_t<decltype(std::declval<std::ostream&>()
<< std::declval<T>())>>
: std::true_type {};
} // namespace internal
template <typename Key>
class KeyNotFound : public std::exception {
public:
KeyNotFound(const Key& key) : message_(get_message(key)) {}
const char* what() const noexcept override { return message_.c_str(); }
private:
static std::string get_message(const Key& key) {
if constexpr (internal::is_printable<Key>::value) {
std::stringstream ss;
ss << "LRU cache: Key not found: " << key;
return ss.str();
}
return "LRU cache: Key not found";
}
std::string message_;
};
} // namespace lru_cache
#endif // LRU_CACHE_EXCEPTION_H_
| 1,054
|
C++
|
.h
| 33
| 28
| 73
| 0.667653
|
nitnelave/lru_cache
| 33
| 12
| 1
|
MPL-2.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,754
|
qevdevtouchhandlerthread.cpp
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchhandlerthread.cpp
|
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qevdevtouchhandlerthread.h"
#include <linux/input.h>
#include <math.h>
#include <QGuiApplication>
#include <QHash>
#include <QLoggingCategory>
#include <QSocketNotifier>
#include <QStringList>
#include <QTouchDevice>
#include <mutex>
QT_BEGIN_NAMESPACE
QEvdevTouchScreenHandlerThread::QEvdevTouchScreenHandlerThread(const QString &device, const QString &spec,
QObject *parent, KoboFbScreen *koboFbScreen) :
m_device(device),
m_spec(spec),
m_handler(nullptr),
m_touchDeviceRegistered(false),
m_touchUpdatePending(false),
m_filterWindow(nullptr),
m_touchRate(-1),
koboFbScreen(koboFbScreen)
{
start();
}
QEvdevTouchScreenHandlerThread::~QEvdevTouchScreenHandlerThread()
{
quit();
wait();
}
void QEvdevTouchScreenHandlerThread::run()
{
m_handler = new QEvdevTouchScreenHandler(m_device, m_spec, nullptr, koboFbScreen);
if (m_handler->isFiltered())
connect(m_handler, &QEvdevTouchScreenHandler::touchPointsUpdated, this,
&QEvdevTouchScreenHandlerThread::scheduleTouchPointUpdate);
// Report the registration to the parent thread by invoking the method asynchronously
QMetaObject::invokeMethod(this, "notifyTouchDeviceRegistered", Qt::QueuedConnection);
exec();
delete m_handler;
m_handler = nullptr;
}
bool QEvdevTouchScreenHandlerThread::isTouchDeviceRegistered() const
{
return m_touchDeviceRegistered;
}
void QEvdevTouchScreenHandlerThread::notifyTouchDeviceRegistered()
{
m_touchDeviceRegistered = true;
emit touchDeviceRegistered();
}
void QEvdevTouchScreenHandlerThread::scheduleTouchPointUpdate()
{
QWindow *window = QGuiApplication::focusWindow();
if (window != m_filterWindow)
{
if (m_filterWindow)
m_filterWindow->removeEventFilter(this);
m_filterWindow = window;
if (m_filterWindow)
m_filterWindow->installEventFilter(this);
}
if (m_filterWindow)
{
m_touchUpdatePending = true;
m_filterWindow->requestUpdate();
}
}
bool QEvdevTouchScreenHandlerThread::eventFilter(QObject *object, QEvent *event)
{
if (m_touchUpdatePending && object == m_filterWindow && event->type() == QEvent::UpdateRequest)
{
m_touchUpdatePending = false;
filterAndSendTouchPoints();
}
return false;
}
void QEvdevTouchScreenHandlerThread::filterAndSendTouchPoints()
{
QRect winRect = m_handler->d->screenGeometry();
if (winRect.isNull())
return;
float vsyncDelta = 1.0f / QGuiApplication::primaryScreen()->refreshRate();
QHash<int, FilteredTouchPoint> filteredPoints;
m_handler->d->m_mutex.lock();
double time = m_handler->d->m_timeStamp;
double lastTime = m_handler->d->m_lastTimeStamp;
double touchDelta = time - lastTime;
if (m_touchRate < 0 || touchDelta > vsyncDelta)
{
// We're at the very start, with nothing to go on, so make a guess
// that the touch rate will be somewhere in the range of half a vsync.
// This doesn't have to be accurate as we will calibrate it over time,
// but it gives us a better starting point so calibration will be
// slightly quicker. If, on the other hand, we already have an
// estimate, we'll leave it as is and keep it.
if (m_touchRate < 0)
m_touchRate = (1.0 / QGuiApplication::primaryScreen()->refreshRate()) / 2.0;
}
else
{
// Update our estimate for the touch rate. We're making the assumption
// that this value will be mostly accurate with the occational bump,
// so we're weighting the existing value high compared to the update.
const double ratio = 0.9;
m_touchRate = sqrt(m_touchRate * m_touchRate * ratio + touchDelta * touchDelta * (1.0 - ratio));
}
QList<QWindowSystemInterface::TouchPoint> points = m_handler->d->m_touchPoints;
QList<QWindowSystemInterface::TouchPoint> lastPoints = m_handler->d->m_lastTouchPoints;
m_handler->d->m_mutex.unlock();
for (int i = 0; i < points.size(); ++i)
{
QWindowSystemInterface::TouchPoint &tp = points[i];
QPointF pos = tp.normalPosition;
FilteredTouchPoint f;
QWindowSystemInterface::TouchPoint ltp;
ltp.id = -1;
for (int j = 0; j < lastPoints.size(); ++j)
{
if (lastPoints.at(j).id == tp.id)
{
ltp = lastPoints.at(j);
break;
}
}
QPointF velocity;
if (lastTime != 0 && ltp.id >= 0)
velocity = (pos - ltp.normalPosition) / m_touchRate;
if (m_filteredPoints.contains(tp.id))
{
f = m_filteredPoints.take(tp.id);
f.x.update(pos.x(), velocity.x(), vsyncDelta);
f.y.update(pos.y(), velocity.y(), vsyncDelta);
pos = QPointF(f.x.position(), f.y.position());
}
else
{
f.x.initialize(pos.x(), velocity.x());
f.y.initialize(pos.y(), velocity.y());
// Make sure the first instance of a touch point we send has the
// 'pressed' state.
if (tp.state != Qt::TouchPointPressed)
tp.state = Qt::TouchPointPressed;
}
tp.velocity = QVector2D(f.x.velocity() * winRect.width(), f.y.velocity() * winRect.height());
qreal filteredNormalizedX = f.x.position() + f.x.velocity() * m_handler->d->m_prediction / 1000.0;
qreal filteredNormalizedY = f.y.position() + f.y.velocity() * m_handler->d->m_prediction / 1000.0;
// Clamp to the screen
tp.normalPosition =
QPointF(qBound<qreal>(0, filteredNormalizedX, 1), qBound<qreal>(0, filteredNormalizedY, 1));
qreal x = winRect.x() + (tp.normalPosition.x() * (winRect.width() - 1));
qreal y = winRect.y() + (tp.normalPosition.y() * (winRect.height() - 1));
tp.area.moveCenter(QPointF(x, y));
// Store the touch point for later so we can release it if we've
// missed the actual release between our last update and this.
f.touchPoint = tp;
// Don't store the point for future reference if it is a release.
if (tp.state != Qt::TouchPointReleased)
filteredPoints[tp.id] = f;
}
for (QHash<int, FilteredTouchPoint>::const_iterator it = m_filteredPoints.constBegin(),
end = m_filteredPoints.constEnd();
it != end; ++it)
{
const FilteredTouchPoint &f = it.value();
QWindowSystemInterface::TouchPoint tp = f.touchPoint;
tp.state = Qt::TouchPointReleased;
tp.velocity = QVector2D();
points.append(tp);
}
m_filteredPoints = filteredPoints;
qDebug() << "sending points:" << points.first().normalPosition;
QWindowSystemInterface::handleTouchEvent(nullptr, m_handler->touchDevice(), points);
}
QT_END_NAMESPACE
| 9,017
|
C++
|
.cpp
| 213
| 36.018779
| 109
| 0.660392
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,755
|
kobobuttonintegration.cpp
|
Rain92_qt5-kobo-platform-plugin/src/kobobuttonintegration.cpp
|
#include "kobobuttonintegration.h"
#define KEY_LIGHT 90
#define KEY_HOME 102
#define KEY_POWER 116
#define KEY_SLEEP_COVER 59
#define KEY_PAGE_UP 193
#define KEY_PAGE_DOWN 194
#define EVENT_REPEAT 2
#define EVENT_PRESS 1
#define EVENT_RELEASE 0
#define OFF 0
#define ON 1
KoboButtonIntegration::KoboButtonIntegration(QObject *parent, const QString &inputDevice, bool debug)
: QObject(parent), debug(debug), isInputCaptured(false)
{
inputHandle = open(inputDevice.toStdString().c_str(), O_RDONLY);
socketNotifier = new QSocketNotifier(inputHandle, QSocketNotifier::Read);
connect(socketNotifier, &QSocketNotifier::activated, this, &KoboButtonIntegration::activity);
socketNotifier->setEnabled(true);
captureInput();
}
KoboButtonIntegration::~KoboButtonIntegration()
{
releaseInput();
delete socketNotifier;
close(inputHandle);
}
void KoboButtonIntegration::captureInput()
{
if (isInputCaptured || inputHandle == -1)
return;
if (debug)
qDebug("KoboKb: Attempting to capture input...");
int res = ioctl(inputHandle, EVIOCGRAB, ON);
if (res == 0)
isInputCaptured = true;
else if (debug)
qDebug() << "KoboKb: Capture keyboard input error:" << res;
}
void KoboButtonIntegration::releaseInput()
{
if (!isInputCaptured || inputHandle == -1)
return;
if (debug)
qDebug("KoboKb: attempting to release input...");
if (ioctl(inputHandle, EVIOCGRAB, OFF) == 0)
isInputCaptured = false;
else if (debug)
qDebug("KoboKb: release keyboard input: error");
}
void KoboButtonIntegration::activity(int)
{
socketNotifier->setEnabled(false);
input_event in;
read(inputHandle, &in, sizeof(input_event));
KoboKey code;
if (KoboPhysicalKeyMap.contains(in.code) && !(in.code == KEY_SLEEP_COVER && in.value == EVENT_REPEAT))
{
code = KoboPhysicalKeyMap[in.code];
QEvent::Type eventType = in.value == EVENT_PRESS ? QEvent::KeyPress : QEvent::KeyRelease;
QKeyEvent keyEvent(eventType, code, Qt::NoModifier);
QObject *focusObject = qGuiApp->focusObject();
if (focusObject)
QGuiApplication::sendEvent(focusObject, &keyEvent);
if (debug)
qDebug() << "found focusobject:" << (focusObject != nullptr) << "in.type:" << in.type
<< " | in.code: " << in.code << " | code:" << code << " | "
<< (in.value ? "pressed" : "released");
}
socketNotifier->setEnabled(true);
}
| 2,535
|
C++
|
.cpp
| 71
| 30.380282
| 106
| 0.674457
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,756
|
koboplatformintegration.cpp
|
Rain92_qt5-kobo-platform-plugin/src/koboplatformintegration.cpp
|
#include "koboplatformintegration.h"
#include <QtEventDispatcherSupport/private/qgenericunixeventdispatcher_p.h>
#include <QtFbSupport/private/qfbbackingstore_p.h>
#include <QtFbSupport/private/qfbwindow_p.h>
#include <QtFontDatabaseSupport/private/qgenericunixfontdatabase_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtServiceSupport/private/qgenericunixservices_p.h>
#include <qevdevtouchmanager_p.h>
#include <qpa/qplatforminputcontextfactory_p.h>
KoboPlatformIntegration::KoboPlatformIntegration(const QStringList ¶mList)
: m_paramList(paramList),
m_primaryScreen(nullptr),
m_inputContext(nullptr),
m_fontDb(new QGenericUnixFontDatabase),
m_services(new QGenericUnixServices),
m_kbdMgr(nullptr),
koboKeyboard(nullptr),
koboAdditions(nullptr),
debug(false)
{
koboDevice = determineDevice();
if (!m_primaryScreen)
m_primaryScreen = new KoboFbScreen(paramList, &koboDevice);
}
KoboPlatformIntegration::~KoboPlatformIntegration()
{
QWindowSystemInterface::handleScreenRemoved(m_primaryScreen);
}
void KoboPlatformIntegration::initialize()
{
if (m_primaryScreen->initialize())
QWindowSystemInterface::handleScreenAdded(m_primaryScreen);
else
qWarning("kobofb: Failed to initialize screen");
m_inputContext = QPlatformInputContextFactory::create();
createInputHandlers();
qWarning("kobofb: Finished initialization.");
}
bool KoboPlatformIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
switch (cap)
{
case ThreadedPixmaps:
return false;
case WindowManagement:
return false;
default:
return QPlatformIntegration::hasCapability(cap);
}
}
QPlatformBackingStore *KoboPlatformIntegration::createPlatformBackingStore(QWindow *window) const
{
return new QFbBackingStore(window);
}
QPlatformWindow *KoboPlatformIntegration::createPlatformWindow(QWindow *window) const
{
return new QFbWindow(window);
}
QAbstractEventDispatcher *KoboPlatformIntegration::createEventDispatcher() const
{
return createUnixEventDispatcher();
}
QList<QPlatformScreen *> KoboPlatformIntegration::screens() const
{
QList<QPlatformScreen *> list;
list.append(m_primaryScreen);
return list;
}
QPlatformFontDatabase *KoboPlatformIntegration::fontDatabase() const
{
return m_fontDb.data();
}
QPlatformServices *KoboPlatformIntegration::services() const
{
return m_services.data();
}
void KoboPlatformIntegration::createInputHandlers()
{
QString touchscreenDevice(koboDevice.touchDev);
QRegularExpression touchDevRx("touchscreen_device=(.*)");
QRegularExpression touchSwapXYRx("touchscreen_swap_xy=(.*)");
QRegularExpression touchInvXRx("touchscreen_invert_x=(.*)");
QRegularExpression touchInvYRx("touchscreen_invert_y=(.*)");
QRegularExpression touchRangeXRx("touchscreen_max_range_x=(.*)");
QRegularExpression touchRangeYRx("touchscreen_max_range_y=(.*)");
QRegularExpression touchRangeFlipRx("touchscreen_flip_axes_limit=(.*)");
bool useHWScreenLimits = true;
bool manualRangeFlip = false;
int touchRangeX = 0;
int touchRangeY = 0;
bool experimentaltouchhandler = false;
auto screenrot = m_primaryScreen->getScreenRotation();
for (const QString &arg : qAsConst(m_paramList))
{
if (arg.contains("debug"))
debug = true;
QRegularExpressionMatch match;
if (arg.contains(touchDevRx, &match))
touchscreenDevice = match.captured(1);
if (arg.contains(touchSwapXYRx, &match) && match.captured(1).toInt() > 0)
{
koboDevice.touchscreenSettings.swapXY = true;
}
if (arg.contains(touchInvXRx, &match) && match.captured(1).toInt() > 0)
{
koboDevice.touchscreenSettings.invertX = true;
}
if (arg.contains(touchInvYRx, &match) && match.captured(1).toInt() > 0)
{
koboDevice.touchscreenSettings.invertY = true;
}
if (arg.contains(touchRangeXRx, &match))
{
touchRangeX = match.captured(1).toInt();
}
if (arg.contains(touchRangeYRx, &match))
{
touchRangeY = match.captured(1).toInt();
}
if (arg.contains(touchRangeFlipRx, &match) && match.captured(1).toInt() > 0)
{
manualRangeFlip = true;
}
if(arg.contains("experimentaltouchhandler"))
{
experimentaltouchhandler = true;
}
}
bool flipTouchscreenAxes = koboDevice.touchscreenSettings.swapXY ^ (screenrot & 1);
if (manualRangeFlip)
flipTouchscreenAxes = !flipTouchscreenAxes;
if (useHWScreenLimits && touchRangeX == 0)
touchRangeX = flipTouchscreenAxes ? koboDevice.height : koboDevice.width;
if (useHWScreenLimits && touchRangeY == 0)
touchRangeY = flipTouchscreenAxes ? koboDevice.width : koboDevice.height;
QString evdevTouchArgs(touchscreenDevice);
if (koboDevice.touchscreenSettings.swapXY)
evdevTouchArgs += ":swapxy";
if (koboDevice.touchscreenSettings.invertX)
evdevTouchArgs += ":invertx";
if (koboDevice.touchscreenSettings.invertY)
evdevTouchArgs += ":inverty";
if (touchRangeX > 0)
evdevTouchArgs += QString(":hw_range_x_max=%1").arg(touchRangeX);
if (touchRangeY > 0)
evdevTouchArgs += QString(":hw_range_y_max=%1").arg(touchRangeY);
if(experimentaltouchhandler)
evdevTouchArgs += ":experimentaltouchhandler";
evdevTouchArgs += QString(":screenwidth=%1").arg(koboDevice.width);
evdevTouchArgs += QString(":screenheight=%1").arg(koboDevice.height);
evdevTouchArgs += QString(":screenrotation=%1").arg(screenrot * 90);
new QEvdevTouchManager("EvdevTouch", evdevTouchArgs, this, m_primaryScreen);
koboKeyboard = new KoboButtonIntegration(this, koboDevice.ntxDev, debug);
koboAdditions = new KoboPlatformAdditions(this, koboDevice);
if (debug)
qDebug() << "device:" << koboDevice.modelName << koboDevice.modelNumber << '\n'
<< "screen:" << koboDevice.width << koboDevice.height << "dpi:" << koboDevice.dpi;
}
QPlatformNativeInterface *KoboPlatformIntegration::nativeInterface() const
{
return const_cast<KoboPlatformIntegration *>(this);
}
KoboDeviceDescriptor *KoboPlatformIntegration::deviceDescriptor()
{
return &koboDevice;
}
QFunctionPointer KoboPlatformIntegration::platformFunction(const QByteArray &function) const
{
if (function == KoboPlatformFunctions::setFrontlightLevelIdentifier())
return QFunctionPointer(setFrontlightLevelStatic);
else if (function == KoboPlatformFunctions::getBatteryLevelIdentifier())
return QFunctionPointer(getBatteryLevelStatic);
else if (function == KoboPlatformFunctions::isBatteryChargingIdentifier())
return QFunctionPointer(isBatteryChargingStatic);
else if (function == KoboPlatformFunctions::setFullScreenRefreshModeIdentifier())
return QFunctionPointer(setFullScreenRefreshModeStatic);
else if (function == KoboPlatformFunctions::clearScreenIdentifier())
return QFunctionPointer(clearScreenStatic);
else if (function == KoboPlatformFunctions::enableDitheringIdentifier())
return QFunctionPointer(enableDitheringStatic);
else if (function == KoboPlatformFunctions::doManualRefreshIdentifier())
return QFunctionPointer(doManualRefreshStatic);
else if (function == KoboPlatformFunctions::getKoboDeviceDescriptorIdentifier())
return QFunctionPointer(getKoboDeviceDescriptorStatic);
else if (function == KoboPlatformFunctions::testInternetConnectionIdentifier())
return QFunctionPointer(testInternetConnectionStatic);
else if (function == KoboPlatformFunctions::enableWiFiConnectionIdentifier())
return QFunctionPointer(enableWiFiConnectionStatic);
else if (function == KoboPlatformFunctions::disableWiFiConnectionIdentifier())
return QFunctionPointer(disableWiFiConnectionStatic);
return 0;
}
void KoboPlatformIntegration::setFrontlightLevelStatic(int val, int temp)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->koboAdditions->setFrontlightLevel(val, temp);
}
int KoboPlatformIntegration::getBatteryLevelStatic()
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
return self->koboAdditions->getBatteryLevel();
}
bool KoboPlatformIntegration::isBatteryChargingStatic()
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
return self->koboAdditions->isBatteryCharging();
}
void KoboPlatformIntegration::setFullScreenRefreshModeStatic(WaveForm waveform)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->m_primaryScreen->setFullScreenRefreshMode(waveform);
}
void KoboPlatformIntegration::clearScreenStatic(bool waitForCompleted)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->m_primaryScreen->clearScreen(waitForCompleted);
}
void KoboPlatformIntegration::enableDitheringStatic(bool softwareDithering, bool hardwareDithering)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->m_primaryScreen->enableDithering(softwareDithering, hardwareDithering);
}
void KoboPlatformIntegration::doManualRefreshStatic(QRect region)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->m_primaryScreen->doManualRefresh(region);
}
KoboDeviceDescriptor KoboPlatformIntegration::getKoboDeviceDescriptorStatic()
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
return *self->deviceDescriptor();
}
void KoboPlatformIntegration::enableWiFiConnectionStatic()
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->wifiManager.enableWiFiConnection();
}
void KoboPlatformIntegration::disableWiFiConnectionStatic()
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
self->wifiManager.disableWiFiConnection();
}
bool KoboPlatformIntegration::testInternetConnectionStatic(int timeout)
{
KoboPlatformIntegration *self =
static_cast<KoboPlatformIntegration *>(QGuiApplicationPrivate::platformIntegration());
return self->wifiManager.testInternetConnection(timeout);
}
| 10,992
|
C++
|
.cpp
| 258
| 37.251938
| 99
| 0.753371
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,758
|
kobodevicedescriptor.cpp
|
Rain92_qt5-kobo-platform-plugin/src/kobodevicedescriptor.cpp
|
#include "kobodevicedescriptor.h"
#include <fcntl.h>
#include <linux/fb.h>
#include <private/qcore_unix_p.h> // overrides QT_OPEN
#include <sys/ioctl.h>
#include <unistd.h>
// Kobo Touch A/B:
KoboDeviceDescriptor KoboTrilogyAB = {
.device = KoboTouchAB,
.mark = 3,
.dpi = 200,
.hasKeys = true,
.touchscreenSettings{.swapXY = false, .hasMultitouch = false},
.frontlightSettings = {.hasFrontLight = false},
};
// Kobo Touch C:
KoboDeviceDescriptor KoboTrilogyC = {
.device = KoboTouchC,
.mark = 4,
.dpi = 200,
.hasKeys = true,
.touchscreenSettings{.swapXY = false, .hasMultitouch = false},
.frontlightSettings = {.hasFrontLight = false},
};
// Kobo Mini:
KoboDeviceDescriptor KoboPixie = {
.device = KoboMini,
.mark = 4,
.dpi = 200,
.touchscreenSettings{.hasMultitouch = false},
.frontlightSettings = {.hasFrontLight = false},
};
// Kobo Glo:
KoboDeviceDescriptor KoboKraken = {
.device = KoboGlo,
.mark = 4,
.dpi = 212,
.touchscreenSettings{.hasMultitouch = false},
};
// Kobo Glo HD:
KoboDeviceDescriptor KoboAlyssum = {
.device = KoboGloHD,
.mark = 6,
.dpi = 300,
};
// Kobo Touch 2.0:
KoboDeviceDescriptor KoboPika = {
.device = KoboTouch2,
.mark = 6,
.dpi = 167,
.frontlightSettings = {.hasFrontLight = false},
};
// Kobo Aura:
KoboDeviceDescriptor KoboPhoenix = {
.device = KoboAura,
.mark = 5,
.dpi = 212,
// NOTE: AFAICT, the Aura was the only one explicitly requiring REAGL requests...
.isREAGL = true,
};
// Kobo Aura HD:
KoboDeviceDescriptor KoboDragon = {
.device = KoboAuraHD,
.mark = 4,
.dpi = 265,
.touchscreenSettings{.hasMultitouch = false},
};
// Kobo Aura H2O:
KoboDeviceDescriptor KoboDahlia = {
.device = KoboAuraH2O,
.mark = 5,
.dpi = 265,
};
// Kobo Aura H2O2:
KoboDeviceDescriptor KoboSnow = {
.device = KoboAuraH2O2_v1,
.mark = 6,
.dpi = 265,
.touchscreenSettings = {.invertX = false},
.frontlightSettings =
{
.hasNaturalLight = true,
.frontlightDevWhite = "/sys/class/backlight/lm3630a_ledb",
.frontlightDevRed = "/sys/class/backlight/lm3630a_led",
.frontlightDevGreen = "/sys/class/backlight/lm3630a_leda",
},
};
// Kobo Aura H2O2, Rev2:
//- @fixme Check if the Clara fix actually helps here... (#4015)
KoboDeviceDescriptor KoboSnowRev2 = {
.device = KoboAuraH2O2_v2,
.mark = 7,
.dpi = 265,
.frontlightSettings =
{
.hasNaturalLight = true,
.frontlightDevWhite = "/sys/class/backlight/lm3630a_ledb",
.frontlightDevRed = "/sys/class/backlight/lm3630a_leda",
},
};
// Kobo Aura One:
KoboDeviceDescriptor KoboDaylight = {
.device = KoboAuraOne,
.mark = 6,
.dpi = 300,
.frontlightSettings = {.hasNaturalLight = true,
.frontlightDevWhite = "/sys/class/backlight/lm3630a_led1b",
.frontlightDevRed = "/sys/class/backlight/lm3630a_led1a",
.frontlightDevGreen = "/sys/class/backlight/lm3630a_ledb"},
};
// Kobo Aura second edition:
KoboDeviceDescriptor KoboStar = {
.device = KoboAura2,
.mark = 6,
.dpi = 212,
};
// Kobo Aura second edition, Rev 2:
KoboDeviceDescriptor KoboStarRev2 = {
.device = KoboAura2_v2,
.mark = 7,
.dpi = 212,
};
// Kobo Clara HD:
KoboDeviceDescriptor KoboNova = {
.device = KoboClaraHD,
.mark = 7,
.dpi = 300,
.canToggleChargingLED = true,
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
.naturalLightInverted = true,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/backlight/lm3630a_led/color",
},
};
// Kobo Forma:
// NOTE: Right now, we enforce Portrait orientation on startup to avoid getting touch coordinates wrong,
// no matter the rotation we were started from (c.f., platform/kobo/koreader.sh).
// NOTE: For the FL, assume brightness is WO, and actual_brightness is RO!
// i.e., we could have a real KoboPowerD:frontlightIntensityHW() by reading actual_brightness ;).
// NOTE: Rotation events *may* not be enabled if Nickel has never been brought up in that power cycle.
// i.e., this will affect KSM users.
// c.f., https://github.com/koreader/koreader/pull/4414#issuecomment-449652335
// There's also a CM_ROTARY_ENABLE command, but which seems to do as much nothing as the STATUS one...
KoboDeviceDescriptor KoboFrost = {
.device = KoboForma,
.mark = 7,
.dpi = 300,
.hasKeys = true,
.canToggleChargingLED = true,
.hasGSensor = true,
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
// Warmth goes from 0 to 10 on the .device's side (our own internal scale is still normalized
// to [0...100]) NOTE: Those three extra keys are *MANDATORY* if .frontlightDevMixer is set!
.naturalLightInverted = true,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/backlight/tlc5947_bl/color",
},
};
// Kobo Libra:
// NOTE: Assume the same quirks as the Forma apply.
KoboDeviceDescriptor KoboStorm = {
.device = KoboLibraH2O,
.mark = 7,
.dpi = 300,
.hasKeys = true,
.canToggleChargingLED = true,
.hasGSensor = true,
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
.naturalLightInverted = true,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/backlight/lm3630a_led/color",
},
// NOTE: The Libra apparently suffers from a mysterious issue where completely innocuous
// WAIT_FOR_UPDATE_COMPLETE ioctls
// will mysteriously fail with a timeout (5s)...
// This obviously leads to *terrible* user experience, so, until more is understood avout the
// issue, bypass this ioctl on this .device. c.f.,
// https://github.com/koreader/koreader/issues/7340
.hasReliableMxcWaitFor = false,
};
// Kobo Nia:
KoboDeviceDescriptor KoboLuna = {
.device = KoboNia,
.mark = 7,
.dpi = 212,
.canToggleChargingLED = true,
};
// Kobo Elipsa
KoboDeviceDescriptor KoboEuropa = {
.device = KoboElipsa,
.mark = 8,
.dpi = 227,
.canToggleChargingLED = true,
.hasGSensor = true,
.isSunxi = true,
.batterySysfs = "/sys/class/power_supply/battery",
.ntxDev = "/dev/input/by-path/platform-ntx_event0-event",
.touchDev = "/dev/input/by-path/platform-0-0010-event",
};
// Kobo Sage
KoboDeviceDescriptor KoboCadmus = {
.device = KoboSage,
.mark = 8,
.dpi = 300,
.canToggleChargingLED = true,
.hasGSensor = true,
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
.naturalLightInverted = false,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/leds/aw99703-bl_FL1/color",
},
.isSunxi = true,
.batterySysfs = "/sys/class/power_supply/battery",
.ntxDev = "/dev/input/by-path/platform-ntx_event0-event",
.touchDev = "/dev/input/by-path/platform-0-0010-event",
};
// Kobo Libra 2
KoboDeviceDescriptor KoboIo = {
.device = KoboLibra2,
.mark = 7,
.dpi = 300,
.canToggleChargingLED = true,
.hasGSensor = true,
.touchscreenSettings{.invertX = false},
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
.naturalLightInverted = true,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/leds/aw99703-bl_FL1/color",
},
.batterySysfs = "/sys/class/power_supply/battery",
};
// Kobo Clara 2E
KoboDeviceDescriptor KoboGoldfinch = {
.device = KoboClara2E,
.mark = 7,
.dpi = 300,
.canToggleChargingLED = true,
.hasGSensor = true,
.frontlightSettings =
{
.hasNaturalLight = true,
.hasNaturalLightMixer = true,
.naturalLightInverted = true,
.naturalLightMin = 0,
.naturalLightMax = 10,
.frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness",
.frontlightDevMixer = "/sys/class/leds/aw99703-bl_FL1/color",
},
.batterySysfs = "/sys/class/power_supply/battery",
.powerDev = "/dev/input/by-path/platform-bd71828-pwrkey-event",
};
static QString exec(const char *cmd)
{
std::array<char, 128> buffer;
QString result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe)
{
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
{
result += buffer.data();
}
return result.trimmed();
}
static QRect determineGeometry(const fb_var_screeninfo &vinfo)
{
int xoff = vinfo.xoffset;
int yoff = vinfo.yoffset;
int w = vinfo.xres;
int h = vinfo.yres;
return QRect(xoff, yoff, w, h);
}
static QSizeF determinePhysicalSize(const fb_var_screeninfo &vinfo, const QSize &res, int dpi = 300)
{
int mmWidth = 0, mmHeight = 0;
if (vinfo.width != 0 && vinfo.height != 0 && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX)
{
mmWidth = vinfo.width;
mmHeight = vinfo.height;
}
else
{
mmWidth = qRound(res.width() * 25.4 / dpi);
mmHeight = qRound(res.height() * 25.4 / dpi);
}
return QSize(mmWidth, mmHeight);
}
KoboDeviceDescriptor determineDevice()
{
auto deviceName = exec("/bin/kobo_config.sh 2>/dev/null");
auto modelNumberStr = exec("cut -f 6 -d ',' /mnt/onboard/.kobo/version | sed -e 's/^[0-]*//'");
int modelNumber = modelNumberStr.toInt();
KoboDeviceDescriptor device;
if (deviceName == "trilogy")
{
if (modelNumber == 310)
device = KoboTrilogyAB;
else // if (modelNumber == 320)
device = KoboTrilogyC;
}
else if (deviceName == "pixie")
{
device = KoboPixie;
}
else if (deviceName == "kraken")
{
device = KoboKraken;
}
else if (deviceName == "alyssum")
{
device = KoboAlyssum;
}
else if (deviceName == "pika")
{
device = KoboPika;
}
else if (deviceName == "phoenix")
{
device = KoboPhoenix;
}
else if (deviceName == "dragon")
{
device = KoboDragon;
}
else if (deviceName == "dahlia")
{
device = KoboDahlia;
}
else if (deviceName == "snow")
{
if (modelNumber == 374)
device = KoboSnow;
else // if (modelNumber == 378)
device = KoboSnowRev2;
}
else if (deviceName == "daylight")
{
device = KoboDaylight;
}
else if (deviceName == "star")
{
if (modelNumber == 375)
device = KoboStar;
else // if (modelNumber == 379)
device = KoboStarRev2;
}
else if (deviceName == "nova")
{
device = KoboNova;
}
else if (deviceName == "frost")
{
device = KoboFrost;
}
else if (deviceName == "storm")
{
device = KoboStorm;
}
else if (deviceName == "luna")
{
device = KoboLuna;
}
else if (deviceName == "europa")
{
device = KoboEuropa;
}
else if (deviceName == "cadmus")
{
device = KoboCadmus;
}
else if (deviceName == "io")
{
device = KoboIo;
}
else if (deviceName == "goldfinch")
{
device = KoboGoldfinch;
}
else
{
device = KoboTrilogyC;
}
QString fbDevice = QLatin1String("/dev/fb0");
if (!QFile::exists(fbDevice))
fbDevice = QLatin1String("/dev/graphics/fb0");
if (!QFile::exists(fbDevice))
{
qWarning("Unable to figure out framebuffer device. Specify it manually.");
// return false;
}
int mFbFd = -1;
if (access(fbDevice.toLatin1().constData(), R_OK | W_OK) == 0)
mFbFd = QT_OPEN(fbDevice.toLatin1().constData(), O_RDWR);
if (mFbFd == -1)
{
if (access(fbDevice.toLatin1().constData(), R_OK) == 0)
mFbFd = QT_OPEN(fbDevice.toLatin1().constData(), O_RDONLY);
}
// Open the device
if (mFbFd == -1)
{
qErrnoWarning(errno, "Failed to open framebuffer %s", qPrintable(fbDevice));
// return false;
}
fb_var_screeninfo vinfo;
if (ioctl(mFbFd, FBIOGET_VSCREENINFO, &vinfo))
{
qErrnoWarning(errno, "Error reading variable information");
}
QRect geometry = determineGeometry(vinfo);
auto mPhysicalSize = determinePhysicalSize(vinfo, geometry.size(), device.dpi);
device.width = geometry.width();
device.height = geometry.height();
device.physicalWidth = mPhysicalSize.width();
device.physicalHeight = mPhysicalSize.height();
device.modelName = deviceName;
device.modelNumber = modelNumber;
close(mFbFd);
return device;
}
| 13,786
|
C++
|
.cpp
| 447
| 24.914989
| 108
| 0.619603
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,759
|
kobowifimanager.cpp
|
Rain92_qt5-kobo-platform-plugin/src/kobowifimanager.cpp
|
#include "kobowifimanager.h"
#include <QDebug>
#include <QFile>
#include <QString>
#include <QThread>
KoboWifiManager::KoboWifiManager() : process(nullptr) {}
KoboWifiManager::~KoboWifiManager()
{
if (process)
{
process->disconnect();
stopProcess();
}
}
void KoboWifiManager::executeShell(const char* command)
{
if (!process)
{
process.reset(new QProcess());
QObject::connect(process.data(), &QProcess::readyReadStandardOutput,
[&]() { qDebug() << process->readAllStandardOutput(); });
QObject::connect(process.data(), &QProcess::readyReadStandardError,
[&]() { qDebug() << process->readAllStandardError(); });
}
stopProcess();
process->start("/bin/sh", {}, QProcess::ReadWrite);
process->waitForStarted();
process->write(command);
process->write("\nexit\n");
process->waitForFinished();
}
void KoboWifiManager::stopProcess()
{
if (process)
if (process->state() != QProcess::NotRunning)
process->close();
}
bool KoboWifiManager::testInternetConnection(int timeout)
{
QString cmd = QString("ping -c 1 -q -W %1 1.1.1.1 2>&1 >/dev/null").arg(timeout);
int res = system(cmd.toLocal8Bit());
return res == 0;
}
void KoboWifiManager::enableWiFiConnection()
{
QFile restoreWifiFile(":/scripts/restore-wifi.sh");
restoreWifiFile.open(QIODevice::ReadOnly);
QByteArray restoreWifiScript = restoreWifiFile.readAll();
restoreWifiFile.close();
executeShell(restoreWifiScript.data());
}
void KoboWifiManager::disableWiFiConnection()
{
QFile disableWifiFile(":/scripts/disable-wifi.sh");
disableWifiFile.open(QIODevice::ReadOnly);
QByteArray disableWifiScript = disableWifiFile.readAll();
disableWifiFile.close();
executeShell(disableWifiScript.data());
}
| 1,867
|
C++
|
.cpp
| 59
| 26.79661
| 85
| 0.681337
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,760
|
koboplatformadditions.cpp
|
Rain92_qt5-kobo-platform-plugin/src/koboplatformadditions.cpp
|
#include "koboplatformadditions.h"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <QCoreApplication>
#include <QDir>
#include <QTextStream>
#include <cmath>
#include <string>
QString str_from_file(const QString& fileName)
{
QString result;
QFile file(fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in(&file);
result = in.readLine().trimmed();
}
return result;
}
int int_from_file(const QString& fileName)
{
return str_from_file(fileName).toInt();
}
static void write_light_value(const QString& file, int value)
{
QFile f(file);
if (f.open(QIODevice::WriteOnly))
{
f.write(QString::number(value).toLatin1());
f.flush();
f.close();
}
}
static void set_light_value(const QString& dir, int value)
{
write_light_value(dir + "/bl_power", value > 0 ? 31 : 0);
write_light_value(dir + "/brightness", value);
}
static bool ntx_io_write(int port, int value)
{
int fd = -1, retval = -1;
if ((fd = ::open("/dev/ntx_io", O_RDWR)) != -1)
{
retval = ioctl(fd, port, value);
close(fd);
}
return retval != -1;
}
static int ntx_io_read(int port)
{
int fd = -1, retval = -1, output;
if ((fd = ::open("/dev/ntx_io", O_RDWR)) != -1)
{
retval = ioctl(fd, port, &output);
close(fd);
}
if (retval == -1)
return -1;
return output;
}
KoboPlatformAdditions::KoboPlatformAdditions(QObject* parent, const KoboDeviceDescriptor& device)
: QObject(parent), device(device)
{
}
int KoboPlatformAdditions::getBatteryLevel() const
{
return int_from_file(device.batterySysfs + "/capacity");
}
bool KoboPlatformAdditions::isBatteryCharging() const
{
return str_from_file(device.batterySysfs + "/status") == "Charging";
}
bool KoboPlatformAdditions::isUsbConnected() const
{
return ntx_io_read(108) == 1;
}
void KoboPlatformAdditions::setStatusLedEnabled(bool enabled)
{
ntx_io_write(101, enabled ? 1 : 0);
}
void KoboPlatformAdditions::setFrontlightLevel(int val, int temp)
{
if (!device.frontlightSettings.hasFrontLight)
return;
val = qMax(device.frontlightSettings.frontlightMin, qMin(val, device.frontlightSettings.frontlightMax));
temp = qMax(device.frontlightSettings.naturalLightMin,
qMin(temp, device.frontlightSettings.naturalLightMax));
if (device.frontlightSettings.hasNaturalLight)
{
setNaturalBrightness(val, temp);
}
else
{
ntx_io_write(241, val);
}
}
void KoboPlatformAdditions::setNaturalBrightness(int brig, int temp)
{
QString fWhite = device.frontlightSettings.frontlightDevWhite,
fRed = device.frontlightSettings.frontlightDevRed,
fGreen = device.frontlightSettings.frontlightDevGreen,
fMixer = device.frontlightSettings.frontlightDevMixer;
if (device.frontlightSettings.hasNaturalLightMixer)
{
if (fWhite != "")
write_light_value(fWhite, brig);
if (fMixer != "")
write_light_value(fMixer, temp);
}
else
{
static const int white_gain = 25;
static const int red_gain = 24;
static const int green_gain = 24;
static const int white_offset = -25;
static const int red_offset = 0;
static const int green_offset = -65;
static const double exponent = 0.25;
double red = 0.0, green = 0.0, white = 0.0;
if (brig > 0)
{
white = std::min(white_gain * pow(brig, exponent) *
pow(device.frontlightSettings.naturalLightMax - temp, exponent) +
white_offset,
255.0);
}
if (temp > 0)
{
red = std::min(red_gain * pow(brig, exponent) * pow(temp, exponent) + red_offset, 255.0);
green = std::min(green_gain * pow(brig, exponent) * pow(temp, exponent) + green_offset, 255.0);
}
white = std::max(white, 0.0);
red = std::max(red, 0.0);
green = std::max(green, 0.0);
if (fWhite != "")
set_light_value(fWhite, floor(white));
if (fRed != "")
set_light_value(fRed, floor(red));
if (fGreen != "")
set_light_value(fGreen, floor(green));
}
}
| 4,420
|
C++
|
.cpp
| 145
| 24.468966
| 108
| 0.624442
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,761
|
dither.cpp
|
Rain92_qt5-kobo-platform-plugin/src/dither.cpp
|
#include "dither.h"
#define SIMD_NEON_PREFECH_SIZE 384
static inline uint32_t div255(uint32_t v)
{
uint32_t _v = v + 128;
return ((_v >> 8U) + _v) >> 8U;
}
static inline uint8_t dither_o8x8(unsigned short int x, unsigned short int y, uint8_t v)
{
// c.f.,
// https://github.com/ImageMagick/ImageMagick/blob/ecfeac404e75f304004f0566557848c53030bad6/config/thresholds.xml#L107
static const uint8_t threshold_map_o8x8[] = {
1, 49, 13, 61, 4, 52, 16, 64, 33, 17, 45, 29, 36, 20, 48, 32, 9, 57, 5, 53, 12, 60,
8, 56, 41, 25, 37, 21, 44, 28, 40, 24, 3, 51, 15, 63, 2, 50, 14, 62, 35, 19, 47, 31,
34, 18, 46, 30, 11, 59, 7, 55, 10, 58, 6, 54, 43, 27, 39, 23, 42, 26, 38, 22};
// Constants:
// Quantum = 8; Levels = 16; map Divisor = 65
// QuantumRange = 0xFF
// QuantumScale = 1.0 / QuantumRange
//
// threshold = QuantumScale * v * ((L-1) * (D-1) + 1)
// NOTE: The initial computation of t (specifically, what we pass to DIV255) would overflow an uint8_t.
// With a Q8 input value, we're at no risk of ever underflowing, so, keep to unsigned maths.
// Technically, an uint16_t would be wide enough, but it gains us nothing,
// and requires a few explicit casts to make GCC happy ;).
uint32_t t = div255(v * ((15U << 6U) + 1U));
// level = t / (D-1);
const uint32_t l = (t >> 6U);
// t -= l * (D-1);
t = (t - (l << 6U));
// map width & height = 8
// c = ClampToQuantum((l+(t >= map[(x % mw) + mw * (y % mh)])) * QuantumRange / (L-1));
const uint32_t q = ((l + (t >= threshold_map_o8x8[(x & 7U) + 8U * (y & 7U)])) * 17U);
// NOTE: We're doing unsigned maths, so, clamping is basically MIN(q, UINT8_MAX) ;).
// The only overflow we should ever catch should be for a few white (v = 0xFF) input pixels
// that get shifted to the next step (i.e., q = 272 (0xFF + 17)).
return (q > UINT8_MAX ? UINT8_MAX : (uint8_t)q);
}
#ifdef __ARM_NEON__
static inline uint16x4_t vdiv255(uint32x4_t vec)
{
uint32x4_t vc128 = vdupq_n_u32(128);
uint32x4_t vec_v = vaddq_u32(vec, vc128);
uint32x4_t res = vshrq_n_u32(vaddq_u32(vshrq_n_u32(vec_v, 8), vec_v), 8);
uint16x4_t res_downcast = vmovn_u32(res);
return res_downcast;
}
void dither_NEON(uint8_t* bufferDest, uint8_t* bufferSrc, int width, int height)
{
static const uint8_t threshold_map_o8x8[] = {
1, 49, 13, 61, 4, 52, 16, 64, 33, 17, 45, 29, 36, 20, 48, 32, 9, 57, 5, 53, 12, 60,
8, 56, 41, 25, 37, 21, 44, 28, 40, 24, 3, 51, 15, 63, 2, 50, 14, 62, 35, 19, 47, 31,
34, 18, 46, 30, 11, 59, 7, 55, 10, 58, 6, 54, 43, 27, 39, 23, 42, 26, 38, 22};
int x = 0, y = 0, cp = 0;
int size = width * height;
if (width >= 8)
{
uint16_t cx = ((15U << 6) + 1U);
uint16x8_t vc1 = vdupq_n_u16(1);
uint16x8_t vc255 = vdupq_n_u16(255);
uint16x4_t vcx = vdup_n_u16(cx);
__builtin_prefetch(bufferSrc + SIMD_NEON_PREFECH_SIZE);
uint8x8_t vecn = vld1_u8(bufferSrc);
int line_leftover = (8 - width) & 7; // (8 - width % 8) % 8
for (y = 0, cp = 0; y < height; y++, cp -= line_leftover)
{
for (x = 0; x < width && cp + 8 <= size; x += 8, cp += 8)
{
// uint8x8_t vecn = vld1_u8((uchar*)buffer.data() + cp);
uint16x8_t vec = vmovl_u8(vecn);
uint16x4_t vec_1 = vget_low_u16(vec);
uint16x4_t vec_2 = vget_high_u16(vec);
uint32x4_t vect0_1 = vmull_u16(vec_1, vcx);
uint32x4_t vect0_2 = vmull_u16(vec_2, vcx);
uint16x4_t vect_1 = vdiv255(vect0_1);
uint16x4_t vect_2 = vdiv255(vect0_2);
uint16x8_t vect = vcombine_u16(vect_1, vect_2);
uint16x8_t vecl = vshrq_n_u16(vect, 6);
vect = vsubq_u16(vect, vshlq_n_u16(vecl, 6));
uint8x8_t vecthreshn = vld1_u8(&threshold_map_o8x8[(x & 7U) + 8U * (y & 7U)]);
uint16x8_t vecthresh = vmovl_u8(vecthreshn);
uint16x8_t vecm = vcgeq_u16(vect, vecthresh);
uint16x8_t vecl2 = vaddq_u16(vecl, vc1);
uint16x8_t vecq = vbslq_u16(vecm, vecl2, vecl);
vecq = vmulq_n_u16(vecq, 17);
vecq = vminq_u16(vecq, vc255);
uint8x8_t vecqb = vmovn_u16(vecq);
// load next chunk before writing back
if (cp + 16 <= size)
{
int offset = cp + 8;
if (x + 8 >= width)
offset -= line_leftover;
__builtin_prefetch(bufferSrc + offset + SIMD_NEON_PREFECH_SIZE);
vecn = vld1_u8(bufferSrc + offset);
}
vst1_u8(bufferDest + cp, vecqb);
}
}
// wind back loop increments
cp -= 8 - line_leftover;
x -= 8;
y -= 1;
}
// take care of leftovers
for (; y < height; y++)
for (; x < width; x++, cp++)
bufferDest[cp] = dither_o8x8(x, y, bufferSrc[cp]);
}
#endif
void dither_fallback(uint8_t* bufferDst, uint8_t* bufferSrc, int width, int height)
{
for (int y = 0, p = 0; y < height; y++)
for (int x = 0; x < width; x++, p++)
bufferDst[p] = dither_o8x8(x, y, bufferSrc[p]);
}
void ditherBuffer(uint8_t* bufferDest, uint8_t* bufferSrc, int width, int height)
{
#ifdef __ARM_NEON__
dither_NEON(bufferDest, bufferSrc, width, height);
#else
dither_fallback(bufferDest, bufferSrc, width, height);
#endif
}
void ditherBufferInplace(uint8_t* buffer, int width, int height)
{
#ifdef __ARM_NEON__
dither_NEON(buffer, buffer, width, height);
#else
dither_fallback(buffer, buffer, width, height);
#endif
}
const uint8_t VALUES_12BPP[] = {0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255};
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define CLAMPED(x, xmin, xmax) MAX((xmin), MIN((xmax), (x)))
// Floyd-Steinberg dither uses constants 7/16 5/16 3/16 and 1/16
// But instead of using real arythmetic, I will use integer on by
// applying shifting ( << 8 )
// When use the constants, don't foget to shift back the result ( >> 8 )
#define f7_16 112 // const int f7 = (7 << 8) / 16;
#define f5_16 80 // const int f5 = (5 << 8) / 16;
#define f3_16 48 // const int f3 = (3 << 8) / 16;
#define f1_16 16 // const int f1 = (1 << 8) / 16;
// Color Floyd-Steinberg dither using 4 bit per color plane
void ditherFloydSteinberg_(uint8_t* dest, uint8_t* src, int width, int height)
{
const int size = width * height;
if (src != dest)
std::memcpy(dest, src, size);
for (int y = 0, i = 0; y < height; y++)
{
for (int x = 0; x < width; x++, i++)
{
const uint8_t oldVal = dest[i];
int newVal = VALUES_12BPP[oldVal >> 4];
dest[i] = newVal;
int cerrorB = oldVal - newVal;
int errorIdx = i + 1;
if (x + 1 < width)
dest[i + 1] = CLAMPED(dest[errorIdx] + ((cerrorB * f7_16) >> 8), 0, 255);
errorIdx += width - 2;
if (x - 1 > 0 && y + 1 < height)
dest[i + width - 1] = CLAMPED(dest[errorIdx] + ((cerrorB * f3_16) >> 8), 0, 255);
errorIdx++;
if (y + 1 < height)
dest[i + width + 0] = CLAMPED(dest[errorIdx] + ((cerrorB * f5_16) >> 8), 0, 255);
errorIdx++;
if (x + 1 < width && y + 1 < height)
dest[i + width + 1] = CLAMPED(dest[errorIdx] + ((cerrorB * f1_16) >> 8), 0, 255);
}
}
}
// Color Floyd-Steinberg dither using 4 bit per color plane
void ditherFloydSteinberg(uint8_t* dest, uint8_t* src, int width, int height)
{
const int size = width * height;
int16_t* errorB = (int16_t*)malloc(size * sizeof(int16_t));
memset(errorB, 0, size * sizeof(int16_t));
for (int y = 0, offset = 0, i = 0; y < height; y++, offset += width)
{
for (int x = 0; x < width; x++, i++)
{
const uint8_t oldVal = src[offset + x];
int oldValErr = oldVal + (errorB[i] >> 8);
// The error could produce values beyond the borders, so need to keep the color in range
int idxB = CLAMPED(oldVal + (errorB[i] >> 8), 0, 255);
int newVal = VALUES_12BPP[idxB >> 4]; // x >> 4 is the same as x / 16
dest[offset + x] = newVal;
int quantError = oldValErr - newVal;
if (x + 1 < width)
errorB[i + 1] += (quantError * f7_16);
if (x - 1 > 0 && y + 1 < height)
errorB[i + width - 1] += (quantError * f3_16);
if (y + 1 < height)
errorB[i + width + 0] += (quantError * f5_16);
if (x + 1 < width && y + 1 < height)
errorB[i + width + 1] += (quantError * f1_16);
}
}
free(errorB);
}
// Color Floyd-Steinberg dither using 4 bit per color plane
void ditherFloydSteinbergN(uint8_t* dest, uint8_t* src, int width, int height)
{
const int size = width * height;
int16_t* errorB = (int16_t*)malloc(size * sizeof(int16_t));
memset(errorB, 0, size * sizeof(int16_t));
int16_t* errorLine = (int16_t*)malloc(width * sizeof(int16_t));
for (int y = 0, offset = 0, i = 0; y < height; y++, offset += width)
{
for (int x = 0; x < width; x++, i++)
{
const uint8_t oldVal = src[offset + x];
int oldValErr = oldVal + (errorB[i] >> 8);
// The error could produce values beyond the borders, so need to keep the color in range
int idxB = CLAMPED(oldVal + (errorB[i] >> 8), 0, 255);
int newVal = VALUES_12BPP[idxB >> 4]; // x >> 4 is the same as x / 16
dest[offset + x] = newVal;
int quantError = oldValErr - newVal;
errorLine[x] = quantError;
int errorIdx = i + 1;
if (x + 1 < width)
errorB[errorIdx] += (quantError * f7_16);
}
if (y + 1 < height)
{
int x = 0;
{
int16_t quantError = errorLine[x];
// errorB[i + x - 1] += (quantError * f3_16);
errorB[i + x + 0] += (quantError * f5_16);
errorB[i + x + 1] += (quantError * f1_16);
}
for (x = 1; x + 7 < width - 1; x += 8)
{
int16x8_t quantErrorv = vld1q_s16(&errorLine[x]);
int16x8_t multv1 = vmulq_n_s16(quantErrorv, f3_16);
int16x8_t resErrorv1 = vld1q_s16(&errorB[i + x - 1]);
int16x8_t resAddv1 = vaddq_s16(resErrorv1, multv1);
vst1q_s16(&errorB[i + x - 1], resAddv1);
int16x8_t multv2 = vmulq_n_s16(quantErrorv, f5_16);
int16x8_t resErrorv2 = vld1q_s16(&errorB[i + x]);
int16x8_t resAddv2 = vaddq_s16(resErrorv2, multv2);
vst1q_s16(&errorB[i + x], resAddv2);
int16x8_t multv3 = vmulq_n_s16(quantErrorv, f1_16);
int16x8_t resErrorv3 = vld1q_s16(&errorB[i + x + 1]);
int16x8_t resAddv3 = vaddq_s16(resErrorv3, multv3);
vst1q_s16(&errorB[i + x + 1], resAddv3);
}
for (; x < width; x++)
{
int16_t quantError = errorLine[x];
errorB[i + x - 1] += (quantError * f3_16);
errorB[i + x + 0] += (quantError * f5_16);
if (x + 1 < width)
errorB[i + x + 1] += (quantError * f1_16);
}
}
}
free(errorB);
free(errorLine);
}
| 11,842
|
C++
|
.cpp
| 263
| 35.779468
| 122
| 0.524509
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,762
|
qevdevtouchmanager.cpp
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchmanager.cpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qguiapplication_p.h>
#include <private/qinputdevicemanager_p_p.h>
#include <QGuiApplication>
#include <QLoggingCategory>
#include <QStringList>
#include "qevdevtouchhandlerthread.h"
#include "qevdevtouchmanager_p.h"
QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(qLcEvdevTouch)
Q_DECLARE_LOGGING_CATEGORY(qLcEvdevTouch2)
Q_DECLARE_LOGGING_CATEGORY(qLcEvdevTouch3)
QEvdevTouchManager::QEvdevTouchManager(const QString &key, const QString &specification, QObject *parent, KoboFbScreen *koboFbScreen)
: QObject(parent), koboFbScreen(koboFbScreen)
{
Q_UNUSED(key);
if (qEnvironmentVariableIsSet("QT_QPA_EVDEV_DEBUG"))
{
const_cast<QLoggingCategory &>(qLcEvdevTouch()).setEnabled(QtDebugMsg, true);
const_cast<QLoggingCategory &>(qLcEvdevTouch2()).setEnabled(QtDebugMsg, true);
const_cast<QLoggingCategory &>(qLcEvdevTouch3()).setEnabled(QtDebugMsg, true);
}
QString spec = QString::fromLocal8Bit(qgetenv("QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS"));
if (spec.isEmpty())
spec = specification;
m_spec = spec;
auto args = spec.splitRef(QLatin1Char(':'));
for (const QStringRef &arg : qAsConst(args))
{
if (arg.startsWith(QLatin1String("/dev/")))
{
// if device is specified try to use it
devicePaths.append(arg.toString());
}
else
{
if (!spec.isEmpty())
spec += QLatin1Char(':');
// build new specification without /dev/ elements
spec += arg;
}
}
for (const QString &device : qAsConst(devicePaths))
addDevice(device);
}
QEvdevTouchManager::~QEvdevTouchManager() {}
void QEvdevTouchManager::addDevice(const QString &deviceNode)
{
qCDebug(qLcEvdevTouch, "evdevtouch: Adding device at %ls", qUtf16Printable(deviceNode));
auto handler = std::unique_ptr<QEvdevTouchScreenHandlerThread>{
new QEvdevTouchScreenHandlerThread(deviceNode, m_spec, this, koboFbScreen)};
if (handler)
{
connect(handler.get(), &QEvdevTouchScreenHandlerThread::touchDeviceRegistered, this,
&QEvdevTouchManager::updateInputDeviceCount);
m_activeDevices.push_back({deviceNode, std::move(handler)});
}
else
{
qWarning("evdevtouch: Failed to open touch device %ls", qUtf16Printable(deviceNode));
}
}
void QEvdevTouchManager::removeDevice(const QString &deviceNode)
{
for (uint i = 0; i < m_activeDevices.size(); i++)
{
if (m_activeDevices[i].deviceNode == deviceNode)
{
m_activeDevices.erase(m_activeDevices.begin() + i);
qCDebug(qLcEvdevTouch, "evdevtouch: Removing device at %ls", qUtf16Printable(deviceNode));
updateInputDeviceCount();
}
}
}
void QEvdevTouchManager::updateInputDeviceCount()
{
int registeredTouchDevices = 0;
for (const auto &device : m_activeDevices)
{
if (device.handler->isTouchDeviceRegistered())
++registeredTouchDevices;
}
qCDebug(qLcEvdevTouch,
"evdevtouch: Updating QInputDeviceManager device count: %d touch devices, %d pending handler(s)",
registeredTouchDevices, m_activeDevices.size() - registeredTouchDevices);
QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())
->setDeviceCount(QInputDeviceManager::DeviceTypeTouch, registeredTouchDevices);
}
QT_END_NAMESPACE
| 5,386
|
C++
|
.cpp
| 126
| 37.984127
| 133
| 0.703131
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,763
|
qevdevtouchdata2.cpp
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchdata2.cpp
|
#include "qevdevtouchdata2.h"
#include <QGuiApplication>
#include <QLoggingCategory>
#include "kobofbscreen.h"
#include "qevdevtouchhandler.h"
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(qLcEvdevTouch3, "qt.qpa.input")
QPointF QEvdevTouchScreenData2::transformTouchPoint(const QPointF &p, bool up)
{
auto canonical_rota = fbink_rota_native_to_canonical(fbink_state->current_rota);
int32_t dim_swap;
QPointF canonical_pos;
QPointF translated_pos;
if ((canonical_rota & 1U) == 0U)
{
// Canonical rotation is even (UR/UD)
dim_swap = (int32_t)fbink_state->screen_width;
}
else
{
// Canonical rotation is odd (CW/CCW)
dim_swap = (int32_t)fbink_state->screen_height;
}
// NOTE: The following was borrowed from my experiments with this in InkVT ;).
// Deal with device-specific rotation quirks...
// c.f., https://github.com/koreader/koreader/blob/master/frontend/device/kobo/device.lua
if (fbink_state->device_id == DEVICE_KOBO_TOUCH_AB && up)
{
// The Touch A/B does something... weird.
// The frame that reports a contact lift does the coordinates transform for us...
// That makes this a NOP for this frame only...
canonical_pos = p;
}
else if (fbink_state->device_id == DEVICE_KOBO_AURA_H2O_2 ||
fbink_state->device_id == DEVICE_KOBO_LIBRA_2)
{
// Aura H2O²r1 & Libra 2
// !touch_mirrored_x
canonical_pos = p.transposed();
}
else
{
// touch_switch_xy && touch_mirrored_x
canonical_pos.setX(dim_swap - p.y());
canonical_pos.setY(p.x());
}
qCDebug(qLcEvdevTouch3) << "canonical_pos" << canonical_pos;
// And, finally, handle somewhat standard touch translation given the current rotation
// c.f., GestureDetector:adjustGesCoordinate @
// https://github.com/koreader/koreader/blob/master/frontend/device/gesturedetector.lua
switch (canonical_rota)
{
case FB_ROTATE_UR:
translated_pos = canonical_pos;
break;
case FB_ROTATE_CW:
translated_pos.setX( (int32_t)fbink_state->screen_width - canonical_pos.y());
translated_pos.setY( canonical_pos.x());
break;
case FB_ROTATE_UD:
translated_pos.setX( (int32_t)fbink_state->screen_width - canonical_pos.x());
translated_pos.setY( (int32_t)fbink_state->screen_height - canonical_pos.y());
break;
case FB_ROTATE_CCW:
translated_pos.setX( canonical_pos.y());
translated_pos.setY( (int32_t)fbink_state->screen_height - canonical_pos.x());
break;
default:
translated_pos.setX( -1);
translated_pos.setY( -1);
break;
}
return translated_pos;
}
QEvdevTouchScreenData2::QEvdevTouchScreenData2(QEvdevTouchScreenHandler *q_ptr, const QStringList &args, KoboFbScreen * koboFbScreen)
: QEvdevTouchScreenData(q_ptr, args), koboFbScreen(koboFbScreen)
{
qDebug() << "using experimental touchhandler";
fbink_state = koboFbScreen->getFBInkState();
}
void QEvdevTouchScreenData2::processInputEvent(input_event *data)
{
if (data->type == EV_KEY)
{
switch (data->code)
{
case BTN_TOOL_PEN:
m_contacts[m_currentSlot].tool = PEN;
// To detect up/down state on "snow" protocol without weird slot shenanigans...
// It's out-of-band of MT events, so, it unfortunately means *all* contacts,
// not a specific slot...
// (i.e., you won't get an EV_KEY:BTN_TOUCH:0 until *all* contact points have been lifted).
if (data->value > 0)
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
}
else
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
}
break;
case BTN_TOOL_FINGER:
m_contacts[m_currentSlot].tool = FINGER;
if (data->value > 0)
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
}
else
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
}
break;
}
}
else if (data->type == EV_ABS)
{
if(data->code == ABS_MT_TOOL_TYPE)
{
if (data->value == 0)
{
m_contacts[m_currentSlot].tool = FINGER;
}
else if (data->value == 1)
{
m_contacts[m_currentSlot].tool = PEN;
}
}
if (data->code == ABS_MT_POSITION_X || data->code == ABS_X)
{
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_X" << data->value;
m_currentData.x = qBound(hw_range_x_min, data->value, hw_range_x_max);
if (m_singleTouch)
{
m_contacts[m_currentSlot].x = m_currentData.x;
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_X Single Touch";
}
if (m_typeB)
{
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_X Type B";
m_contacts[m_currentSlot].x = m_currentData.x;
if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
}
}
else if (data->code == ABS_MT_POSITION_Y || data->code == ABS_Y)
{
m_currentData.y = qBound(hw_range_y_min, data->value, hw_range_y_max);
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_Y" << data->value;
if (m_singleTouch)
{
m_contacts[m_currentSlot].y = m_currentData.y;
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_Y Single touch";
}
if (m_typeB)
{
qCDebug(qLcEvdevTouch3) << "EV_ABS MT_POS_Y Type B";
m_contacts[m_currentSlot].y = m_currentData.y;
if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
}
}
else if (data->code == ABS_MT_TRACKING_ID)
{
if (fbink_state->is_sunxi && data->value == -1)
{
koboFbScreen->doSunxiPenRefresh();
}
else
{
m_currentData.trackingId = data->value;
// // QT apparently can't handle high tracking IDs well?
// if (m_currentData.trackingId > 2)
// m_currentData.trackingId = 1;
qCDebug(qLcEvdevTouch3) << "EV_ABS TRACKING_ID " << m_currentData.trackingId;
if (m_typeB)
{
if (m_currentData.trackingId == -1)
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
qCDebug(qLcEvdevTouch3) << "EV_ABS TRACKING_ID = -1 touch point released";
}
else if (m_currentData.trackingId != m_contacts[m_currentSlot].trackingId)
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
m_contacts[m_currentSlot].trackingId = m_currentData.trackingId;
qCDebug(qLcEvdevTouch3) << "EV_ABS TRACKING_ID != -1 touch point pressed";
}
}
}
}
else if (data->code == ABS_MT_TOUCH_MAJOR)
{
qCDebug(qLcEvdevTouch3) << "EV_ABS TOUCH_MAJOR";
m_currentData.maj = data->value;
if (data->value == 0 && !m_btnTool)
m_currentData.state = Qt::TouchPointReleased;
if (m_typeB)
m_contacts[m_currentSlot].maj = m_currentData.maj;
}
else if (data->code == ABS_PRESSURE || data->code == ABS_MT_PRESSURE)
{
qCDebug(qLcEvdevTouch3) << "EV_ABS PRESSURE";
qCDebug(qLcEvdevTouch3, "EV_ABS code 0x%x: pressure %d; bounding to [%d,%d]", data->code,
data->value, hw_pressure_min, hw_pressure_max);
m_currentData.pressure = qBound(hw_pressure_min, data->value, hw_pressure_max);
if (m_typeB || m_singleTouch)
m_contacts[m_currentSlot].pressure = m_currentData.pressure;
}
else if (data->code == ABS_MT_SLOT)
{
m_currentSlot = data->value;
qCDebug(qLcEvdevTouch3) << "EV_ABS SLOT";
}
}
else if (data->type == EV_KEY && !m_typeB)
{
qCDebug(qLcEvdevTouch3) << "EV_KEY";
if (data->code == BTN_TOUCH && data->value == 0)
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
qCDebug(qLcEvdevTouch3) << "EV_KEY BTN_TOUCH 0 touchpoint released";
}
// On some devices (Glo HD) ABS_MT_TRACKING_ID starts at 1
// => there will be malformed events with ABS_MT_TRACKING_ID 0 => filter those at addTouchPoint().
if (data->code == BTN_TOUCH && data->value == 1)
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
qCDebug(qLcEvdevTouch3) << "EV_KEY BTN_TOUCH 1 touchpoint pressed";
}
}
else if (data->type == EV_SYN && data->code == SYN_MT_REPORT && m_lastEventType != EV_SYN)
{
qCDebug(qLcEvdevTouch3) << "EV_SYN MT_REPORT && lastEvent was not EV_SYN";
// If there is no tracking id, one will be generated later.
// Until that use a temporary key.
int key = m_currentData.trackingId;
if (key == -1)
key = m_contacts.count();
m_contacts.insert(key, m_currentData);
m_currentData = Contact();
}
else if (data->type == EV_SYN && data->code == SYN_REPORT)
{
qCDebug(qLcEvdevTouch3) << "EV_SYN SYN_REPORT";
// Ensure valid IDs even when the driver does not report ABS_MT_TRACKING_ID.
if (!m_contacts.isEmpty() && m_contacts.constBegin().value().trackingId == -1)
assignIds();
std::unique_lock<QMutex> locker;
if (m_filtered)
locker = std::unique_lock<QMutex>{m_mutex};
// update timestamps
m_lastTimeStamp = m_timeStamp;
m_timeStamp = data->time.tv_sec + data->time.tv_usec / 1000000.0;
m_lastTouchPoints = m_touchPoints;
m_touchPoints.clear();
Qt::TouchPointStates combinedStates;
bool hasPressure = false;
for (auto i = m_contacts.begin(), end = m_contacts.end(); i != end; /*erasing*/)
{
auto it = i++;
Contact &contact(it.value());
if (!contact.state)
continue;
int key = m_typeB ? it.key() : contact.trackingId;
if (!m_typeB && m_lastContacts.contains(key))
{
const Contact &prev(m_lastContacts.value(key));
if (contact.state == Qt::TouchPointReleased)
{
// Copy over the previous values for released points, just in case.
contact.x = prev.x;
contact.y = prev.y;
contact.maj = prev.maj;
}
else
{
contact.state = (prev.x == contact.x && prev.y == contact.y) ? Qt::TouchPointStationary
: Qt::TouchPointMoved;
}
}
// Avoid reporting a contact in released state more than once.
if (!m_typeB && contact.state == Qt::TouchPointReleased && !m_lastContacts.contains(key))
{
m_contacts.erase(it);
qCDebug(qLcEvdevTouch3) << "Erase contact since touchpoint released";
continue;
}
if (contact.pressure)
hasPressure = true;
addTouchPoint(contact, &combinedStates);
}
// Now look for contacts that have disappeared since the last sync.
for (auto it = m_lastContacts.begin(), end = m_lastContacts.end(); it != end; ++it)
{
Contact &contact(it.value());
int key = m_typeB ? it.key() : contact.trackingId;
if (m_typeB)
{
if (contact.trackingId != m_contacts[key].trackingId && contact.state)
{
contact.state = Qt::TouchPointReleased;
addTouchPoint(contact, &combinedStates);
}
}
else
{
if (!m_contacts.contains(key))
{
contact.state = Qt::TouchPointReleased;
addTouchPoint(contact, &combinedStates);
}
}
}
// Remove contacts that have just been reported as released.
for (auto i = m_contacts.begin(), end = m_contacts.end(); i != end; /*erasing*/)
{
auto it = i++;
Contact &contact(it.value());
if (!contact.state)
continue;
if (contact.state == Qt::TouchPointReleased)
{
if (m_typeB)
contact.state = static_cast<Qt::TouchPointState>(0);
else
{
m_contacts.erase(it);
qCDebug(qLcEvdevTouch3) << "Contact Erase since state is released";
}
}
else
{
contact.state = Qt::TouchPointStationary;
}
}
m_lastContacts = m_contacts;
if (!m_typeB && !m_singleTouch)
m_contacts.clear();
if (!m_touchPoints.isEmpty() && (hasPressure || combinedStates != Qt::TouchPointStationary))
reportPoints();
}
qCDebug(qLcEvdevTouch3) << "Contact state:" << m_contacts[0].state;
m_lastEventType = data->type;
}
void QEvdevTouchScreenData2::addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates)
{
// if (contact.x == -1 && contact.y == -1)
// return; // failsafe, for devices with ABS_MT_TRACKING_ID not starting at 0
QWindowSystemInterface::TouchPoint tp;
tp.id = contact.trackingId;
tp.flags = contact.flags;
tp.state = contact.state;
*combinedStates |= tp.state;
// Store the HW coordinates for now, will be updated later.
tp.area = QRectF(0, 0, contact.maj, contact.maj);
tp.area.moveCenter(QPoint(contact.x, contact.y));
tp.pressure = contact.pressure;
tp.rawPositions.append(QPointF(contact.x, contact.y));
auto transformedPos = transformTouchPoint(QPointF(contact.x, contact.y), contact.state == Qt::TouchPointReleased);
// Get a normalized position in range 0..1.
tp.normalPosition = QPointF(transformedPos.x() / qreal(fbink_state->screen_width),
transformedPos.y() / qreal(fbink_state->screen_height));
qCDebug(qLcEvdevTouch3) << "Adding touch point:" << tp.id << tp.uniqueId;
qCDebug(qLcEvdevTouch3) << "Touchpoint raw position:" << tp.rawPositions.last();
qCDebug(qLcEvdevTouch3) << "Touchpoint transformed position:" << transformedPos;
qCDebug(qLcEvdevTouch3) << "Touchpoint normal transformed position:" << tp.normalPosition;
m_touchPoints.append(tp);
}
QT_END_NAMESPACE
| 15,670
|
C++
|
.cpp
| 369
| 30.807588
| 133
| 0.550144
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,764
|
qevdevtouchhandler.cpp
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchhandler.cpp
|
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qevdevtouchhandler.h"
#include <linux/input.h>
#include <math.h>
#include <QGuiApplication>
#include <QHash>
#include <QLoggingCategory>
#include <QSocketNotifier>
#include <QStringList>
#include <QTouchDevice>
#include <mutex>
#include "qevdevtouchdata.h"
#include "qevdevtouchdata2.h"
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(qLcEvdevTouch2, "qt.qpa.input")
#define LONG_BITS (sizeof(long) << 3)
#define NUM_LONGS(bits) (((bits) + LONG_BITS - 1) / LONG_BITS)
static inline bool testBit(long bit, const long *array)
{
return (array[bit / LONG_BITS] >> bit % LONG_BITS) & 1;
}
QEvdevTouchScreenHandler::QEvdevTouchScreenHandler(const QString &device, const QString &spec,
QObject *parent, KoboFbScreen *koboFbScreen)
: QObject(parent), m_notify(nullptr), m_fd(-1), d(nullptr), m_device(nullptr)
{
setObjectName(QLatin1String("Evdev Touch Handler"));
qCDebug(qLcEvdevTouch2) << "spec: " <<spec;
const QStringList args = spec.split(QLatin1Char(':'));
bool experimentaltochdhandler = false;
bool swapxy = false;
bool invertx = false;
bool inverty = false;
int hw_range_x_max_overwrite = 0;
int hw_range_y_max_overwrite = 0;
QRect screenRect;
int screenrotation = 0;
for (int i = 0; i < args.count(); ++i)
{
if (args.at(i).startsWith(QLatin1String("screenwidth")))
{
QString sArg = args.at(i).section(QLatin1Char('='), 1, 1);
bool ok;
uint argValue = sArg.toUInt(&ok);
if (ok)
{
screenRect.setWidth(argValue);
}
}
else if (args.at(i).startsWith(QLatin1String("screenheight")))
{
QString sArg = args.at(i).section(QLatin1Char('='), 1, 1);
bool ok;
uint argValue = sArg.toUInt(&ok);
if (ok)
{
screenRect.setHeight(argValue);
}
}
else if (args.at(i).startsWith(QLatin1String("screenrotation")))
{
QString sArg = args.at(i).section(QLatin1Char('='), 1, 1);
bool ok;
uint argValue = sArg.toUInt(&ok);
if (ok)
{
screenrotation = argValue;
}
}
else if (args.at(i).startsWith(QLatin1String("hw_range_x_max")))
{
QString sArg = args.at(i).section(QLatin1Char('='), 1, 1);
bool ok;
uint argValue = sArg.toUInt(&ok);
if (ok)
{
hw_range_x_max_overwrite = argValue;
}
}
else if (args.at(i).startsWith(QLatin1String("hw_range_y_max")))
{
QString sArg = args.at(i).section(QLatin1Char('='), 1, 1);
bool ok;
uint argValue = sArg.toUInt(&ok);
if (ok)
{
hw_range_y_max_overwrite = argValue;
}
}
else if (args.at(i) == QLatin1String("swapxy"))
{
swapxy = true;
}
else if (args.at(i) == QLatin1String("invertx"))
{
invertx = true;
}
else if (args.at(i) == QLatin1String("inverty"))
{
inverty = true;
}
else if (args.at(i).toLower() == QLatin1String("experimentaltouchhandler"))
{
experimentaltochdhandler = true;
}
}
qCDebug(qLcEvdevTouch2, "evdevtouch: Using device %ls", qUtf16Printable(device));
m_fd = QT_OPEN(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0);
if (m_fd >= 0)
{
m_notify = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);
connect(m_notify, &QSocketNotifier::activated, this, &QEvdevTouchScreenHandler::readData);
}
else
{
qErrnoWarning("evdevtouch: Cannot open input device %ls", qUtf16Printable(device));
return;
}
if(!experimentaltochdhandler)
d = new QEvdevTouchScreenData(this, args);
else
d = new QEvdevTouchScreenData2(this, args, koboFbScreen);
d->setScreenGeometry(screenRect);
qCDebug(qLcEvdevTouch2, "evdevtouch: setting screen rect %d %d", screenRect.width(), screenRect.height());
long absbits[NUM_LONGS(ABS_CNT)];
if (ioctl(m_fd, EVIOCGBIT(EV_ABS, sizeof(absbits)), absbits) >= 0)
{
d->m_typeB = testBit(ABS_MT_SLOT, absbits);
d->m_singleTouch = !testBit(ABS_MT_POSITION_X, absbits);
}
long keybits[NUM_LONGS(KEY_CNT)];
if (ioctl(m_fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits) >= 0)
d->m_btnTool = testBit(BTN_TOOL_FINGER, keybits);
d->deviceNode = device;
qCDebug(qLcEvdevTouch2, "evdevtouch: %ls: Protocol type %c (%s), filtered=%s",
qUtf16Printable(d->deviceNode), d->m_typeB ? 'B' : 'A', d->m_singleTouch ? "single" : "multi",
d->m_filtered ? "yes" : "no");
if (d->m_filtered)
qCDebug(qLcEvdevTouch2, " - prediction=%d", d->m_prediction);
input_absinfo absInfo;
memset(&absInfo, 0, sizeof(input_absinfo));
bool has_x_range = false, has_y_range = false;
if (ioctl(m_fd, EVIOCGABS((d->m_singleTouch ? ABS_X : ABS_MT_POSITION_X)), &absInfo) >= 0)
{
qCDebug(qLcEvdevTouch2, "evdevtouch: %ls: min X: %d max X: %d", qUtf16Printable(device),
absInfo.minimum, absInfo.maximum);
d->hw_range_x_min = absInfo.minimum;
d->hw_range_x_max = hw_range_x_max_overwrite > 0 ? hw_range_x_max_overwrite : absInfo.maximum;
qCDebug(qLcEvdevTouch2, "evdevtouch: overwriting touch x max: %d", hw_range_x_max_overwrite);
has_x_range = true;
}
if (ioctl(m_fd, EVIOCGABS((d->m_singleTouch ? ABS_Y : ABS_MT_POSITION_Y)), &absInfo) >= 0)
{
qCDebug(qLcEvdevTouch2, "evdevtouch: %ls: min Y: %d max Y: %d", qUtf16Printable(device),
absInfo.minimum, absInfo.maximum);
d->hw_range_y_min = absInfo.minimum;
d->hw_range_y_max = hw_range_y_max_overwrite > 0 ? hw_range_y_max_overwrite : absInfo.maximum;
qCDebug(qLcEvdevTouch2, "evdevtouch: overwriting touch y max: %d", hw_range_y_max_overwrite);
has_y_range = true;
}
if (!has_x_range || !has_y_range)
qWarning("evdevtouch: %ls: Invalid ABS limits, behavior unspecified", qUtf16Printable(device));
if (ioctl(m_fd, EVIOCGABS(ABS_PRESSURE), &absInfo) >= 0)
{
qCDebug(qLcEvdevTouch2, "evdevtouch: %ls: min pressure: %d max pressure: %d", qUtf16Printable(device),
absInfo.minimum, absInfo.maximum);
if (absInfo.maximum > absInfo.minimum)
{
d->hw_pressure_min = absInfo.minimum;
d->hw_pressure_max = absInfo.maximum;
}
}
d->m_swapXY = swapxy;
d->m_invertX = invertx;
d->m_invertY = inverty;
if (screenrotation % 90 == 0)
d->m_rotate = (screenrotation + 3600) % 360;
else
d->m_rotate = 0;
char name[1024];
if (ioctl(m_fd, EVIOCGNAME(sizeof(name) - 1), name) >= 0)
{
d->hw_name = QString::fromLocal8Bit(name);
qCDebug(qLcEvdevTouch2, "evdevtouch: %ls: device name: %s", qUtf16Printable(device), name);
}
bool grabSuccess = !ioctl(m_fd, EVIOCGRAB, (void *)1);
if (grabSuccess)
ioctl(m_fd, EVIOCGRAB, (void *)0);
else
qWarning("evdevtouch: The device is grabbed by another process. No events will be read.");
registerTouchDevice();
}
QEvdevTouchScreenHandler::~QEvdevTouchScreenHandler()
{
if (m_fd >= 0)
QT_CLOSE(m_fd);
delete d;
unregisterTouchDevice();
}
bool QEvdevTouchScreenHandler::isFiltered() const
{
return d && d->m_filtered;
}
QTouchDevice *QEvdevTouchScreenHandler::touchDevice() const
{
return m_device;
}
void QEvdevTouchScreenHandler::readData()
{
::input_event buffer[32];
int events = 0;
int n = 0;
for (;;)
{
events = QT_READ(m_fd, reinterpret_cast<char *>(buffer) + n, sizeof(buffer) - n);
if (events <= 0)
goto err;
n += events;
if (n % sizeof(::input_event) == 0)
break;
}
n /= sizeof(::input_event);
for (int i = 0; i < n; ++i)
d->processInputEvent(&buffer[i]);
return;
err:
if (!events)
{
qWarning("evdevtouch: Got EOF from input device");
return;
}
else if (events < 0)
{
if (errno != EINTR && errno != EAGAIN)
{
qErrnoWarning("evdevtouch: Could not read from input device");
if (errno == ENODEV)
{ // device got disconnected -> stop reading
delete m_notify;
m_notify = nullptr;
QT_CLOSE(m_fd);
m_fd = -1;
unregisterTouchDevice();
}
return;
}
}
}
void QEvdevTouchScreenHandler::registerTouchDevice()
{
if (m_device)
return;
m_device = new QTouchDevice;
m_device->setName(d->hw_name);
m_device->setType(QTouchDevice::TouchScreen);
m_device->setCapabilities(QTouchDevice::Position | QTouchDevice::Area);
if (d->hw_pressure_max > d->hw_pressure_min)
m_device->setCapabilities(m_device->capabilities() | QTouchDevice::Pressure);
QWindowSystemInterface::registerTouchDevice(m_device);
}
void QEvdevTouchScreenHandler::unregisterTouchDevice()
{
if (!m_device)
return;
// At app exit the cleanup may have already been done, avoid
// double delete by checking the list first.
if (QWindowSystemInterface::isTouchDeviceRegistered(m_device))
{
QWindowSystemInterface::unregisterTouchDevice(m_device);
delete m_device;
}
m_device = nullptr;
}
QT_END_NAMESPACE
| 11,740
|
C++
|
.cpp
| 311
| 30.874598
| 110
| 0.618223
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,765
|
kobofbscreen.cpp
|
Rain92_qt5-kobo-platform-plugin/src/kobofbscreen.cpp
|
#include "kobofbscreen.h"
#include <QtFbSupport/private/qfbwindow_p.h>
#include <QtGui/QPainter>
// force the compiler to link i2c-tools
extern "C"
{
#include "i2c-tools/include/i2c/smbus.h"
__s32 (*i2c_smbus_read_byte_fp)(int) = &i2c_smbus_read_byte;
}
#define SMALLTHRESHOLD1 60
#define SMALLTHRESHOLD2 40
#define FULLSCREENTOLERANCE 80
static QImage::Format determineFormat(int fbfd, int depth)
{
fb_var_screeninfo info;
if (ioctl(fbfd, FBIOGET_VSCREENINFO, &info))
return QImage::Format_Invalid;
const fb_bitfield rgba[4] = {info.red, info.green, info.blue, info.transp};
QImage::Format format = QImage::Format_Invalid;
switch (depth)
{
case 32:
{
const fb_bitfield argb8888[4] = {{16, 8, 0}, {8, 8, 0}, {0, 8, 0}, {24, 8, 0}};
const fb_bitfield abgr8888[4] = {{0, 8, 0}, {8, 8, 0}, {16, 8, 0}, {24, 8, 0}};
if (memcmp(rgba, argb8888, 4 * sizeof(fb_bitfield)) == 0)
{
format = QImage::Format_ARGB32;
}
else if (memcmp(rgba, argb8888, 3 * sizeof(fb_bitfield)) == 0)
{
format = QImage::Format_RGB32;
}
else if (memcmp(rgba, abgr8888, 3 * sizeof(fb_bitfield)) == 0)
{
format = QImage::Format_RGB32;
// pixeltype = BGRPixel;
}
break;
}
case 24:
{
const fb_bitfield rgb888[4] = {{16, 8, 0}, {8, 8, 0}, {0, 8, 0}, {0, 0, 0}};
const fb_bitfield bgr888[4] = {{0, 8, 0}, {8, 8, 0}, {16, 8, 0}, {0, 0, 0}};
if (memcmp(rgba, rgb888, 3 * sizeof(fb_bitfield)) == 0)
{
format = QImage::Format_RGB888;
}
else if (memcmp(rgba, bgr888, 3 * sizeof(fb_bitfield)) == 0)
{
format = QImage::Format_BGR888;
// pixeltype = BGRPixel;
}
break;
}
case 8:
format = QImage::Format_Grayscale8;
break;
default:
break;
}
return format;
}
KoboFbScreen::KoboFbScreen(const QStringList &args, KoboDeviceDescriptor *koboDevice)
: koboDevice(koboDevice),
mArgs(args),
mFbFd(-1),
debug(false),
mFbScreenImage(),
mBytesPerLine(0),
mBlitter(0),
fbink_state({0}),
memmapInfo({0}),
fbink_cfg({0}),
waitForRefresh(false),
useHardwareDithering(false),
useSoftwareDithering(true)
{
waitForRefresh = false;
useHardwareDithering = false;
waveFormFullscreen = WFM_GC16;
waveFormPartial = WFM_AUTO;
waveFormFast = WFM_A2;
if (koboDevice->isREAGL)
{
this->waveFormPartial = WFM_REAGLD;
this->waveFormFast = WFM_DU;
}
else if (koboDevice->mark == 7)
{
this->waveFormPartial = WFM_REAGL;
this->waveFormFast = WFM_DU;
}
else if (koboDevice->isSunxi)
{
this->waveFormPartial = WFM_REAGL;
this->waveFormFast = WFM_DU;
}
}
KoboFbScreen::~KoboFbScreen()
{
uint8_t grayscale = originalBpp == 8 ? GRAYSCALE_8BIT : 0;
if (fbink_set_fb_info(mFbFd, originalRotation, originalBpp, grayscale, &fbink_cfg) != EXIT_SUCCESS)
{
qDebug() << "Failed to set original rotation and bpp.";
}
if (mFbFd != -1)
{
fbink_close(mFbFd);
}
delete mBlitter;
}
bool KoboFbScreen::initialize()
{
QRegularExpression fbRx("fb=(.*)");
QRegularExpression sizeRx("size=(\\d+)x(\\d+)");
QRegularExpression dpiRx("logicaldpitarget=(\\d+)");
QString fbDevice;
QRect userGeometry;
int logicalDpiTarget = 0;
// Parse arguments
for (const QString &arg : qAsConst(mArgs))
{
QRegularExpressionMatch match;
if (arg.contains(sizeRx, &match))
userGeometry.setSize(QSize(match.captured(1).toInt(), match.captured(2).toInt()));
else if (arg.contains(fbRx, &match))
fbDevice = match.captured(1);
else if (arg.contains(dpiRx, &match))
logicalDpiTarget = match.captured(1).toInt();
else if (arg.startsWith("debug"))
debug = true;
}
fbink_cfg.is_verbose = debug;
fbink_cfg.is_quiet = !debug;
// Open framebuffer and keep it around, then setup globals.
if ((mFbFd = fbink_open()) < EXIT_SUCCESS)
{
qDebug() << "Failed to open the framebuffer";
return false;
}
if (fbink_init(mFbFd, &fbink_cfg) < EXIT_SUCCESS)
{
qDebug() << "Failed to initialize FBInk.";
return false;
}
fbink_get_state(&fbink_cfg, &fbink_state);
originalBpp = fbink_state.bpp;
originalRotation = fbink_state.current_rota;
setScreenRotation(RotationUR);
QFbScreen::initializeCompositor();
if (mFbScreenImage.isNull())
qDebug() << "Error, mFbScreenImage is invalid!";
if (logicalDpiTarget > 0)
{
// qputenv("QT_SCALE_FACTOR_ROUNDING_POLICY ", "PassThrough");
qputenv("QT_SCREEN_SCALE_FACTORS",
QString::number(koboDevice->dpi / (double)logicalDpiTarget, 'g', 8).toLatin1());
}
return true;
}
bool KoboFbScreen::setScreenRotation(ScreenRotation r, int bpp)
{
int8_t rota_native = fbink_rota_canonical_to_native(r);
uint8_t grayscale = bpp == 8 ? GRAYSCALE_8BIT : 0;
int rv = 0;
if ((rv = fbink_set_fb_info(mFbFd, rota_native, bpp, grayscale, &fbink_cfg)) < EXIT_SUCCESS)
{
qDebug() << "Failed to set rotation and bpp:" << rv;
}
fbink_get_state(&fbink_cfg, &fbink_state);
mBytesPerLine = fbink_state.scanline_stride;
koboDevice->width = fbink_state.screen_width;
koboDevice->height = fbink_state.screen_height;
if (debug)
qDebug() << "Screen info:" << fbink_state.screen_width << fbink_state.screen_height
<< "rotation:" << fbink_state.current_rota
<< "rotation canonical:" << fbink_rota_native_to_canonical(fbink_state.current_rota)
<< "bpp:" << fbink_state.bpp;
mGeometry = {0, 0, koboDevice->width, koboDevice->height};
mPhysicalSize = QSizeF(koboDevice->physicalWidth, koboDevice->physicalHeight);
if ((memmapInfo.bufferPtr = fbink_get_fb_pointer(mFbFd, &memmapInfo.bufferSize)) == NULL)
{
qDebug() << "Failed to get fb data or memmap screen";
return false;
}
if (debug)
qDebug() << "Allocated screen buffer. Stride:" << fbink_state.scanline_stride
<< "buffer size:" << memmapInfo.bufferSize;
mDepth = fbink_state.bpp;
mFormat = determineFormat(mFbFd, mDepth);
mFbScreenImage =
QImage(memmapInfo.bufferPtr, mGeometry.width(), mGeometry.height(), mBytesPerLine, mFormat);
return true;
}
ScreenRotation KoboFbScreen::getScreenRotation()
{
return (ScreenRotation)fbink_rota_native_to_canonical(fbink_state.current_rota);
}
FBInkConfig *KoboFbScreen::getFBInkConfig()
{
return &fbink_cfg;
}
FBInkState *KoboFbScreen::getFBInkState()
{
return &fbink_state;
}
void KoboFbScreen::setFullScreenRefreshMode(WaveForm waveform)
{
this->waveFormFullscreen = waveform;
}
void KoboFbScreen::clearScreen(bool waitForCompleted)
{
FBInkRect r = {0, 0, static_cast<unsigned short>(mGeometry.width()),
static_cast<unsigned short>(mGeometry.height())};
fbink_cls(mFbFd, &fbink_cfg, &r, true);
if (waitForCompleted && koboDevice->hasReliableMxcWaitFor)
fbink_wait_for_complete(mFbFd, LAST_MARKER);
}
void KoboFbScreen::enableDithering(bool softwareDithering, bool hardwareDithering)
{
useHardwareDithering = hardwareDithering;
useSoftwareDithering = softwareDithering;
if (useSoftwareDithering)
mScreenImageDither = mScreenImage;
}
void KoboFbScreen::ditherRegion(const QRect ®ion)
{
if (mScreenImageDither.size() != mScreenImage.size())
mScreenImageDither = mScreenImage;
// only dither the lines that were updated
int updateHeight = region.height();
int offset = region.top() * mScreenImage.width();
ditherBuffer(mScreenImageDither.bits() + offset, mScreenImage.bits() + offset, mScreenImage.width(),
updateHeight);
// ditherFloydSteinberg(mScreenImageDither.bits() + offset, mScreenImage.bits() + offset,
// mScreenImage.width(), updateHeight);
}
void KoboFbScreen::doManualRefresh(const QRect ®ion)
{
bool isFullRefresh = region.width() >= mGeometry.width() - FULLSCREENTOLERANCE &&
region.height() >= mGeometry.height() - FULLSCREENTOLERANCE;
bool isSmall = (region.width() < SMALLTHRESHOLD1 && region.height() < SMALLTHRESHOLD1) ||
(region.width() + region.height() < SMALLTHRESHOLD2);
if (isFullRefresh)
fbink_cfg.wfm_mode = this->waveFormFullscreen;
else if (isSmall)
fbink_cfg.wfm_mode = this->waveFormFast;
else
fbink_cfg.wfm_mode = this->waveFormPartial;
fbink_cfg.is_flashing = isFullRefresh;
fbink_refresh(mFbFd, region.top(), region.left(), region.width(), region.height(), &fbink_cfg);
if (waitForRefresh && koboDevice->hasReliableMxcWaitFor)
fbink_wait_for_complete(mFbFd, LAST_MARKER);
}
QRegion KoboFbScreen::doRedraw()
{
QElapsedTimer t;
t.start();
QRegion touched = QFbScreen::doRedraw();
if (touched.isEmpty())
return touched;
QRect r(*touched.begin());
for (const QRect &rect : touched)
r = r.united(rect);
if (!mBlitter)
mBlitter = new QPainter(&mFbScreenImage);
if (useSoftwareDithering)
ditherRegion(r);
mBlitter->setCompositionMode(QPainter::CompositionMode_Source);
for (const QRect &rect : touched)
mBlitter->drawImage(rect, useSoftwareDithering ? mScreenImageDither : mScreenImage, rect);
doManualRefresh(r);
// if (debug)
// qDebug() << "Painted region" << touched << "in" << t.elapsed() << "ms";
return touched;
}
void KoboFbScreen::doSunxiPenRefresh()
{
// NOTE: On sunxi, send a !pen refresh on pen up because otherwise the driver
// softlocks,
// and ultimately trips a reboot watchdog...
// NOTE: Nickel also toggles pen mode *off* before doing that...
// Let's do the same, as we can still somewhat reliably kill the kernel
// one way or another otherwise...
// NOTE: That means that any other competing refresh is potentially dangerous:
// make sure only pen refreshes are sent while in pen mode!
fbink_sunxi_toggle_ntx_pen_mode(mFbFd, false);
const WFM_MODE_INDEX_T pen_wfm = fbink_cfg.wfm_mode;
fbink_cfg.wfm_mode = WFM_GL16;
fbink_refresh(mFbFd, 0, 0, 0, 0, &fbink_cfg);
fbink_cfg.wfm_mode = pen_wfm;
fbink_sunxi_toggle_ntx_pen_mode(mFbFd, true);
}
| 10,875
|
C++
|
.cpp
| 294
| 30.316327
| 104
| 0.633787
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,766
|
qevdevtouchdata.cpp
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchdata.cpp
|
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qevdevtouchdata.h"
#include <linux/input.h>
#include <math.h>
#include <QGuiApplication>
#include <QHash>
#include <QLoggingCategory>
#include <QSocketNotifier>
#include <QStringList>
#include <QTouchDevice>
#include <mutex>
#include "qevdevtouchhandler.h"
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(qLcEvdevTouch, "qt.qpa.input")
Q_LOGGING_CATEGORY(qLcEvents, "qt.qpa.input.events")
QPointF QEvdevTouchScreenData::transformTouchPoint(const QPointF &p)
{
QPointF tp = p;
if (m_swapXY)
tp = tp.transposed();
tp = {m_invertX ? 1 - tp.x() : tp.x(), m_invertY ? 1 - tp.y() : tp.y()};
if (m_rotate == 90)
tp = {tp.y(), 1 - tp.x()};
if (m_rotate == 180)
tp = {1 - tp.x(), 1 - tp.y()};
if (m_rotate == 270)
tp = {1 - tp.y(), tp.x()};
return tp;
}
QEvdevTouchScreenData::QEvdevTouchScreenData(QEvdevTouchScreenHandler *q_ptr, const QStringList &args)
: q(q_ptr),
m_lastEventType(-1),
m_currentSlot(0),
m_timeStamp(0),
m_lastTimeStamp(0),
hw_range_x_min(0),
hw_range_x_max(0),
hw_range_y_min(0),
hw_range_y_max(0),
hw_pressure_min(0),
hw_pressure_max(0),
m_forceToActiveWindow(false),
m_typeB(false),
m_singleTouch(false),
m_btnTool(false),
m_filtered(false),
m_prediction(0)
{
for (const QString &arg : args)
{
if (arg == QStringLiteral("force_window"))
m_forceToActiveWindow = true;
else if (arg == QStringLiteral("filtered"))
m_filtered = true;
else if (arg.startsWith(QStringLiteral("prediction=")))
m_prediction = arg.midRef(11).toInt();
}
}
void QEvdevTouchScreenData::addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates)
{
if (contact.x == -1 && contact.y == -1)
return; // failsafe, for devices with ABS_MT_TRACKING_ID not starting at 0
QWindowSystemInterface::TouchPoint tp;
tp.id = contact.trackingId;
tp.flags = contact.flags;
tp.state = contact.state;
*combinedStates |= tp.state;
// Store the HW coordinates for now, will be updated later.
tp.area = QRectF(0, 0, contact.maj, contact.maj);
tp.area.moveCenter(QPoint(contact.x, contact.y));
tp.pressure = contact.pressure;
// Get a normalized position in range 0..1.
tp.normalPosition = QPointF((contact.x - hw_range_x_min) / qreal(hw_range_x_max - hw_range_x_min),
(contact.y - hw_range_y_min) / qreal(hw_range_y_max - hw_range_y_min));
tp.rawPositions.append(QPointF(contact.x, contact.y));
qCDebug(qLcEvdevTouch) << "Adding touch point:" << tp.id << tp.uniqueId;
qCDebug(qLcEvdevTouch) << "Touchpoint raw position:" << tp.rawPositions.last();
qCDebug(qLcEvdevTouch) << "Touchpoint normal position:" << tp.normalPosition;
tp.normalPosition = transformTouchPoint(tp.normalPosition);
qCDebug(qLcEvdevTouch) << "Touchpoint transformed normal position:" << tp.normalPosition;
m_touchPoints.append(tp);
}
void QEvdevTouchScreenData::processInputEvent(input_event *data)
{
if (data->type == EV_ABS)
{
if (data->code == ABS_MT_POSITION_X || (m_singleTouch && data->code == ABS_X))
{
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_X" << data->value;
m_currentData.x = qBound(hw_range_x_min, data->value, hw_range_x_max);
if (m_singleTouch)
{
m_contacts[m_currentSlot].x = m_currentData.x;
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_X Single Touch";
}
if (m_typeB)
{
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_X Type B";
m_contacts[m_currentSlot].x = m_currentData.x;
if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
}
}
else if (data->code == ABS_MT_POSITION_Y || (m_singleTouch && data->code == ABS_Y))
{
m_currentData.y = qBound(hw_range_y_min, data->value, hw_range_y_max);
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_Y" << data->value;
if (m_singleTouch)
{
m_contacts[m_currentSlot].y = m_currentData.y;
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_Y Single touch";
}
if (m_typeB)
{
qCDebug(qLcEvdevTouch) << "EV_ABS MT_POS_Y Type B";
m_contacts[m_currentSlot].y = m_currentData.y;
if (m_contacts[m_currentSlot].state == Qt::TouchPointStationary)
m_contacts[m_currentSlot].state = Qt::TouchPointMoved;
}
}
else if (data->code == ABS_MT_TRACKING_ID)
{
m_currentData.trackingId = data->value;
// QT apparently can't handle high tracking IDs well?
if (m_currentData.trackingId > 2)
m_currentData.trackingId = 1;
qCDebug(qLcEvdevTouch) << "EV_ABS TRACKING_ID " << m_currentData.trackingId;
if (m_typeB)
{
if (m_currentData.trackingId == -1)
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
qCDebug(qLcEvdevTouch) << "EV_ABS TRACKING_ID = -1 touch point released";
}
else
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
m_contacts[m_currentSlot].trackingId = m_currentData.trackingId;
qCDebug(qLcEvdevTouch) << "EV_ABS TRACKING_ID != -1 touch point pressed";
}
}
}
else if (data->code == ABS_MT_TOUCH_MAJOR)
{
qCDebug(qLcEvdevTouch) << "EV_ABS TOUCH_MAJOR";
m_currentData.maj = data->value;
if (data->value == 0 && !m_btnTool)
m_currentData.state = Qt::TouchPointReleased;
if (m_typeB)
m_contacts[m_currentSlot].maj = m_currentData.maj;
}
else if (data->code == ABS_PRESSURE || data->code == ABS_MT_PRESSURE)
{
qCDebug(qLcEvdevTouch) << "EV_ABS PRESSURE";
if (Q_UNLIKELY(qLcEvents().isDebugEnabled()))
qCDebug(qLcEvents, "EV_ABS code 0x%x: pressure %d; bounding to [%d,%d]", data->code,
data->value, hw_pressure_min, hw_pressure_max);
m_currentData.pressure = qBound(hw_pressure_min, data->value, hw_pressure_max);
if (m_typeB || m_singleTouch)
m_contacts[m_currentSlot].pressure = m_currentData.pressure;
}
else if (data->code == ABS_MT_SLOT)
{
m_currentSlot = data->value;
qCDebug(qLcEvdevTouch) << "EV_ABS SLOT";
}
}
else if (data->type == EV_KEY && !m_typeB)
{
qCDebug(qLcEvdevTouch) << "EV_KEY";
if (data->code == BTN_TOUCH && data->value == 0)
{
m_contacts[m_currentSlot].state = Qt::TouchPointReleased;
qCDebug(qLcEvdevTouch) << "EV_KEY BTN_TOUCH 0 touchpoint released";
}
// On some devices (Glo HD) ABS_MT_TRACKING_ID starts at 1
// => there will be malformed events with ABS_MT_TRACKING_ID 0 => filter those at addTouchPoint().
if (data->code == BTN_TOUCH && data->value == 1)
{
m_contacts[m_currentSlot].state = Qt::TouchPointPressed;
qCDebug(qLcEvdevTouch) << "EV_KEY BTN_TOUCH 1 touchpoint pressed";
}
}
else if (data->type == EV_SYN && data->code == SYN_MT_REPORT && m_lastEventType != EV_SYN)
{
qCDebug(qLcEvdevTouch) << "EV_SYN MT_REPORT && lastEvent was not EV_SYN";
// If there is no tracking id, one will be generated later.
// Until that use a temporary key.
int key = m_currentData.trackingId;
if (key == -1)
key = m_contacts.count();
m_contacts.insert(key, m_currentData);
m_currentData = Contact();
}
else if (data->type == EV_SYN && data->code == SYN_REPORT)
{
qCDebug(qLcEvdevTouch) << "EV_SYN SYN_REPORT";
// Ensure valid IDs even when the driver does not report ABS_MT_TRACKING_ID.
if (!m_contacts.isEmpty() && m_contacts.constBegin().value().trackingId == -1)
assignIds();
std::unique_lock<QMutex> locker;
if (m_filtered)
locker = std::unique_lock<QMutex>{m_mutex};
// update timestamps
m_lastTimeStamp = m_timeStamp;
m_timeStamp = data->time.tv_sec + data->time.tv_usec / 1000000.0;
m_lastTouchPoints = m_touchPoints;
m_touchPoints.clear();
Qt::TouchPointStates combinedStates;
bool hasPressure = false;
for (auto i = m_contacts.begin(), end = m_contacts.end(); i != end; /*erasing*/)
{
auto it = i++;
Contact &contact(it.value());
if (!contact.state)
continue;
int key = m_typeB ? it.key() : contact.trackingId;
if (!m_typeB && m_lastContacts.contains(key))
{
const Contact &prev(m_lastContacts.value(key));
if (contact.state == Qt::TouchPointReleased)
{
// Copy over the previous values for released points, just in case.
contact.x = prev.x;
contact.y = prev.y;
contact.maj = prev.maj;
}
else
{
contact.state = (prev.x == contact.x && prev.y == contact.y) ? Qt::TouchPointStationary
: Qt::TouchPointMoved;
}
}
// Avoid reporting a contact in released state more than once.
if (!m_typeB && contact.state == Qt::TouchPointReleased && !m_lastContacts.contains(key))
{
m_contacts.erase(it);
qCDebug(qLcEvdevTouch) << "Erase contact since touchpoint released";
continue;
}
if (contact.pressure)
hasPressure = true;
addTouchPoint(contact, &combinedStates);
}
// Now look for contacts that have disappeared since the last sync.
for (auto it = m_lastContacts.begin(), end = m_lastContacts.end(); it != end; ++it)
{
Contact &contact(it.value());
int key = m_typeB ? it.key() : contact.trackingId;
if (m_typeB)
{
if (contact.trackingId != m_contacts[key].trackingId && contact.state)
{
contact.state = Qt::TouchPointReleased;
addTouchPoint(contact, &combinedStates);
}
}
else
{
if (!m_contacts.contains(key))
{
contact.state = Qt::TouchPointReleased;
addTouchPoint(contact, &combinedStates);
}
}
}
// Remove contacts that have just been reported as released.
for (auto i = m_contacts.begin(), end = m_contacts.end(); i != end; /*erasing*/)
{
auto it = i++;
Contact &contact(it.value());
if (!contact.state)
continue;
if (contact.state == Qt::TouchPointReleased)
{
if (m_typeB)
contact.state = static_cast<Qt::TouchPointState>(0);
else
{
m_contacts.erase(it);
qCDebug(qLcEvdevTouch) << "Contact Erase since state is released";
}
}
else
{
contact.state = Qt::TouchPointStationary;
}
}
m_lastContacts = m_contacts;
if (!m_typeB && !m_singleTouch)
m_contacts.clear();
if (!m_touchPoints.isEmpty() && (hasPressure || combinedStates != Qt::TouchPointStationary))
reportPoints();
}
qCDebug(qLcEvdevTouch) << "Contact state:" << m_contacts[0].state;
m_lastEventType = data->type;
}
int QEvdevTouchScreenData::findClosestContact(const QHash<int, Contact> &contacts, int x, int y, int *dist)
{
int minDist = -1, id = -1;
for (QHash<int, Contact>::const_iterator it = contacts.constBegin(), ite = contacts.constEnd(); it != ite;
++it)
{
const Contact &contact(it.value());
int dx = x - contact.x;
int dy = y - contact.y;
int dist = dx * dx + dy * dy;
if (minDist == -1 || dist < minDist)
{
minDist = dist;
id = contact.trackingId;
}
}
if (dist)
*dist = minDist;
return id;
}
void QEvdevTouchScreenData::assignIds()
{
QHash<int, Contact> candidates = m_lastContacts, pending = m_contacts, newContacts;
int maxId = -1;
QHash<int, Contact>::iterator it, ite, bestMatch;
while (!pending.isEmpty() && !candidates.isEmpty())
{
int bestDist = -1, bestId = 0;
for (it = pending.begin(), ite = pending.end(); it != ite; ++it)
{
int dist;
int id = findClosestContact(candidates, it->x, it->y, &dist);
if (id >= 0 && (bestDist == -1 || dist < bestDist))
{
bestDist = dist;
bestId = id;
bestMatch = it;
}
}
if (bestDist >= 0)
{
bestMatch->trackingId = bestId;
newContacts.insert(bestId, *bestMatch);
candidates.remove(bestId);
pending.erase(bestMatch);
if (bestId > maxId)
maxId = bestId;
}
}
if (candidates.isEmpty())
{
for (it = pending.begin(), ite = pending.end(); it != ite; ++it)
{
it->trackingId = ++maxId;
newContacts.insert(it->trackingId, *it);
}
}
m_contacts = newContacts;
}
QRect QEvdevTouchScreenData::screenGeometry() const
{
return m_screenGeometry;
}
void QEvdevTouchScreenData::setScreenGeometry(QRect rect)
{
m_screenGeometry = rect;
}
void QEvdevTouchScreenData::reportPoints()
{
QRect winRect = screenGeometry();
if (winRect.isNull())
return;
// const int hw_w = hw_range_x_max - hw_range_x_min;
// const int hw_h = hw_range_y_max - hw_range_y_min;
// Map the coordinates based on the normalized position. QPA expects 'area'
// to be in screen coordinates.
const int pointCount = m_touchPoints.count();
for (int i = 0; i < pointCount; ++i)
{
QWindowSystemInterface::TouchPoint &tp(m_touchPoints[i]);
// Generate a screen position that is always inside the active window
// or the primary screen. Even though we report this as a QRectF, internally
// Qt uses QRect/QPoint so we need to bound the size to winRect.size() - QSize(1, 1)
const qreal wx = winRect.left() + tp.normalPosition.x() * (winRect.width() - 1);
const qreal wy = winRect.top() + tp.normalPosition.y() * (winRect.height() - 1);
// const qreal sizeRatio = (winRect.width() + winRect.height()) / qreal(hw_w + hw_h);
// if (tp.area.width() == -1) // touch major was not provided
tp.area = QRectF(0, 0, 8, 8);
// else
// tp.area = QRectF(0, 0, tp.area.width() * sizeRatio, tp.area.height() * sizeRatio);
tp.area.moveCenter(QPointF(wx, wy));
// Calculate normalized pressure.
if (!hw_pressure_min && !hw_pressure_max)
tp.pressure = tp.state == Qt::TouchPointReleased ? 0 : 1;
else
tp.pressure = (tp.pressure - hw_pressure_min) / qreal(hw_pressure_max - hw_pressure_min);
if (Q_UNLIKELY(qLcEvents().isDebugEnabled()))
qCDebug(qLcEvents) << "reporting" << tp;
qCDebug(qLcEvdevTouch) << "Screen rect:" << winRect;
qCDebug(qLcEvdevTouch) << "Registering touch point:" << tp << tp.state;
}
// Let qguiapp pick the target window.
if (m_filtered)
emit q->touchPointsUpdated();
else
QWindowSystemInterface::handleTouchEvent(nullptr, q->touchDevice(), m_touchPoints);
}
QT_END_NAMESPACE
| 18,468
|
C++
|
.cpp
| 443
| 32.27991
| 110
| 0.575866
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,767
|
dither.h
|
Rain92_qt5-kobo-platform-plugin/src/dither.h
|
#ifndef DITHER_H
#define DITHER_H
#include <stdint.h>
#include <stdlib.h>
#include <cstring>
#ifdef __ARM_NEON__
#include <arm_neon.h>
#endif
void ditherBuffer(uint8_t* bufferDest, uint8_t* bufferSrc, int width, int height);
void ditherBufferInplace(uint8_t* buffer, int width, int height);
void ditherFloydSteinberg(uint8_t* dest, uint8_t* src, int width, int height);
void ditherFloydSteinbergN(uint8_t* dest, uint8_t* src, int width, int height);
#endif // DITHER_H
| 476
|
C++
|
.h
| 13
| 35.153846
| 82
| 0.763676
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,768
|
koboplatformadditions.h
|
Rain92_qt5-kobo-platform-plugin/src/koboplatformadditions.h
|
#ifndef KOBOPLATFORMADDITIONS_H
#define KOBOPLATFORMADDITIONS_H
#include <QObject>
#include "einkenums.h"
#include "kobodevicedescriptor.h"
class KoboPlatformAdditions : public QObject
{
Q_OBJECT
public:
KoboPlatformAdditions(QObject *parent, const KoboDeviceDescriptor &device);
int getBatteryLevel() const;
bool isBatteryCharging() const;
bool isUsbConnected() const;
void setStatusLedEnabled(bool enabled);
void setFrontlightLevel(int val, int temp);
private:
void setNaturalBrightness(int brig, int temp);
private:
KoboDeviceDescriptor device;
};
#endif // KOBOPLATFORMADDITIONS_H
| 632
|
C++
|
.h
| 21
| 26.904762
| 79
| 0.795341
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,769
|
kobodevicedescriptor.h
|
Rain92_qt5-kobo-platform-plugin/src/kobodevicedescriptor.h
|
#ifndef KOBODEVICEDESCRIPTOR_H
#define KOBODEVICEDESCRIPTOR_H
#include <QtCore>
#include <iostream>
enum KoboDevice
{
KoboUnknown,
KoboTouchAB,
KoboTouchC,
KoboMini,
KoboGlo,
KoboGloHD,
KoboTouch2,
KoboAura,
KoboAuraHD,
KoboAuraH2O,
KoboAuraH2O2_v1,
KoboAuraH2O2_v2,
KoboAuraOne,
KoboAura2,
KoboAura2_v2,
KoboClaraHD,
KoboForma,
KoboLibraH2O,
KoboNia,
KoboElipsa,
KoboSage,
KoboLibra2,
KoboClara2E
};
struct TouchscreenSettings
{
bool swapXY = true;
bool invertX = true;
bool invertY = false;
bool hasMultitouch = true;
};
struct FrontlightSettings
{
bool hasFrontLight = true;
int frontlightMin = 0;
int frontlightMax = 100;
bool hasNaturalLight = false;
bool hasNaturalLightMixer = false;
bool naturalLightInverted = false;
int naturalLightMin = 0;
int naturalLightMax = 100;
QString frontlightDevWhite = "/sys/class/backlight/mxc_msp430.0/brightness";
QString frontlightDevMixer = "/sys/class/backlight/lm3630a_led/color";
QString frontlightDevRed = "/sys/class/backlight/lm3630a_led1a";
QString frontlightDevGreen = "/sys/class/backlight/lm3630a_ledb";
};
struct KoboDeviceDescriptor
{
KoboDevice device;
QString modelName;
int modelNumber;
int mark = 6;
int dpi;
int width;
int height;
qreal physicalWidth;
qreal physicalHeight;
bool hasKeys = false;
bool canToggleChargingLED = false;
// New devices *may* be REAGL-aware, but generally don't expect explicit REAGL requests, default to not.
bool isREAGL = false;
// unused for now
bool hasGSensor = false;
TouchscreenSettings touchscreenSettings;
FrontlightSettings frontlightSettings;
// MXCFB_WAIT_FOR_UPDATE_COMPLETE ioctls are generally reliable
bool hasReliableMxcWaitFor = true;
// Sunxi devices require a completely different fb backend...
bool isSunxi = false;
// Standard sysfs path to the battery directory
QString batterySysfs = "/sys/class/power_supply/mc13892_bat";
// Stable path to the NTX input device
QString ntxDev = "/dev/input/event0";
// Stable path to the Touch input device
QString touchDev = "/dev/input/event1";
// Stable path to the Power Button input device
QString powerDev = "null";
};
KoboDeviceDescriptor determineDevice();
#endif // KOBODEVICEDESCRIPTOR_H
| 2,430
|
C++
|
.h
| 86
| 23.930233
| 108
| 0.727897
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,770
|
qevdevtouchdata2.h
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchdata2.h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QEVDEVTOUCHDATA2H_H
#define QEVDEVTOUCHDATA2H_H
#include <linux/input.h>
#include <qpa/qwindowsysteminterface.h>
#include "fbink.h"
#include "kobofbscreen.h"
#include "qevdevtouchdata.h"
#include "qevdevtouchfilter_p.h"
#define ABS_MT_SLOT 0x2f
QT_BEGIN_NAMESPACE
class QEvdevTouchScreenHandler;
class QEvdevTouchScreenData2 : public QEvdevTouchScreenData
{
public:
QEvdevTouchScreenData2(QEvdevTouchScreenHandler *q_ptr, const QStringList &args, KoboFbScreen * koboFbScreen);
QPointF transformTouchPoint(const QPointF &p, bool up);
void processInputEvent(input_event *data) override;
void addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates) override;
private:
FBInkState* fbink_state;
KoboFbScreen * koboFbScreen;
};
QT_END_NAMESPACE
#endif // QEVDEVTOUCH_P_H
| 2,824
|
C++
|
.h
| 63
| 43.253968
| 114
| 0.741724
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,771
|
qevdevtouchmanager_p.h
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchmanager_p.h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QEVDEVTOUCHMANAGER_P_H
#define QEVDEVTOUCHMANAGER_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
//#include <QtInputSupport/private/devicehandlerlist_p.h>
#include <QHash>
#include <QObject>
#include <QSocketNotifier>
#include <memory>
#include "kobofbscreen.h"
QT_BEGIN_NAMESPACE
class QEvdevTouchScreenHandlerThread;
class QEvdevTouchManager : public QObject
{
public:
struct Device
{
QString deviceNode;
std::unique_ptr<QEvdevTouchScreenHandlerThread> handler;
};
QEvdevTouchManager(const QString &key, const QString &spec, QObject *parent, KoboFbScreen *koboFbScreen);
~QEvdevTouchManager();
void addDevice(const QString &deviceNode);
void removeDevice(const QString &deviceNode);
void updateInputDeviceCount();
private:
QString m_spec;
QStringList devicePaths;
std::vector<Device> m_activeDevices;
KoboFbScreen *koboFbScreen;
};
QT_END_NAMESPACE
#endif // QEVDEVTOUCHMANAGER_P_H
| 3,091
|
C++
|
.h
| 79
| 37.151899
| 109
| 0.725242
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,772
|
kobowifimanager.h
|
Rain92_qt5-kobo-platform-plugin/src/kobowifimanager.h
|
#ifndef WIFIMANAGER_H
#define WIFIMANAGER_H
#include <QProcess>
#include <QSharedPointer>
class KoboWifiManager
{
public:
KoboWifiManager();
~KoboWifiManager();
bool testInternetConnection(int timeout);
void enableWiFiConnection();
void disableWiFiConnection();
void stopProcess();
private:
void executeShell(const char* command);
QSharedPointer<QProcess> process;
};
#endif // WIFIMANAGER_H
| 433
|
C++
|
.h
| 18
| 20.833333
| 45
| 0.769042
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,773
|
qevdevtouchhandlerthread.h
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchhandlerthread.h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QEVDEVTOUCHHANDLERTHREAD_H
#define QEVDEVTOUCHHANDLERTHREAD_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/private/qthread_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <QList>
#include <QObject>
#include <QString>
#include <QThread>
#include "qevdevtouchdata.h"
#include "qevdevtouchhandler.h"
QT_BEGIN_NAMESPACE
class QEvdevTouchScreenHandlerThread : public QDaemonThread
{
Q_OBJECT
public:
explicit QEvdevTouchScreenHandlerThread(const QString &device, const QString &spec,
QObject *parent, KoboFbScreen *koboFbScreen);
~QEvdevTouchScreenHandlerThread();
void run() override;
bool isTouchDeviceRegistered() const;
bool eventFilter(QObject *object, QEvent *event) override;
void scheduleTouchPointUpdate();
signals:
void touchDeviceRegistered();
private:
Q_INVOKABLE void notifyTouchDeviceRegistered();
void filterAndSendTouchPoints();
QRect targetScreenGeometry() const;
QString m_device;
QString m_spec;
QEvdevTouchScreenHandler *m_handler;
bool m_touchDeviceRegistered;
bool m_touchUpdatePending;
QWindow *m_filterWindow;
struct FilteredTouchPoint
{
QEvdevTouchFilter x;
QEvdevTouchFilter y;
QWindowSystemInterface::TouchPoint touchPoint;
};
QHash<int, FilteredTouchPoint> m_filteredPoints;
float m_touchRate;
KoboFbScreen *koboFbScreen;
};
QT_END_NAMESPACE
#endif // QEVDEVTOUCH_P_H
| 3,697
|
C++
|
.h
| 95
| 36.021053
| 89
| 0.724176
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,775
|
kobobuttonintegration.h
|
Rain92_qt5-kobo-platform-plugin/src/kobobuttonintegration.h
|
#ifndef KOBOBUTTONINTEGRATION_H
#define KOBOBUTTONINTEGRATION_H
#include <fcntl.h>
#include <linux/input.h>
#include <qevent.h>
#include <qguiapplication.h>
#include <unistd.h>
#include <QDebug>
#include <QSocketNotifier>
#include <iostream>
#include "einkenums.h"
class KoboButtonIntegration : public QObject
{
Q_OBJECT
public:
KoboButtonIntegration(QObject* parent = nullptr, const QString& inputDevice = "/dev/input/event0",
bool debug = false);
~KoboButtonIntegration();
private slots:
void activity(int);
private:
int inputHandle;
QSocketNotifier* socketNotifier;
bool debug;
bool isInputCaptured;
void captureInput();
void releaseInput();
};
#endif // KOBOBUTTONINTEGRATION_H
| 759
|
C++
|
.h
| 29
| 22.551724
| 102
| 0.741667
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,776
|
koboplatformintegration.h
|
Rain92_qt5-kobo-platform-plugin/src/koboplatformintegration.h
|
#ifndef QLINUXFBINTEGRATION_H
#define QLINUXFBINTEGRATION_H
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformnativeinterface.h>
#include <QtCore/QRegularExpression>
#include "kobobuttonintegration.h"
#include "kobofbscreen.h"
#include "koboplatformadditions.h"
#include "koboplatformfunctions.h"
#include "kobowifimanager.h"
class QAbstractEventDispatcher;
class QFbVtHandler;
class QEvdevKeyboardManager;
class KoboPlatformIntegration : public QPlatformIntegration, public QPlatformNativeInterface
{
public:
explicit KoboPlatformIntegration(const QStringList ¶mList);
~KoboPlatformIntegration();
void initialize() override;
bool hasCapability(QPlatformIntegration::Capability cap) const override;
QPlatformWindow *createPlatformWindow(QWindow *window) const override;
QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const override;
QAbstractEventDispatcher *createEventDispatcher() const override;
QPlatformFontDatabase *fontDatabase() const override;
QPlatformServices *services() const override;
QPlatformInputContext *inputContext() const override { return m_inputContext; }
QPlatformNativeInterface *nativeInterface() const override;
QList<QPlatformScreen *> screens() const;
QFunctionPointer platformFunction(const QByteArray &function) const override;
KoboDeviceDescriptor *deviceDescriptor();
private:
void createInputHandlers();
static int getBatteryLevelStatic();
static bool isBatteryChargingStatic();
static void setFrontlightLevelStatic(int val, int temp);
static void setFullScreenRefreshModeStatic(WaveForm waveform);
static void clearScreenStatic(bool waitForCompleted);
static void enableDitheringStatic(bool softwareDithering, bool hardwareDithering);
static void doManualRefreshStatic(QRect region);
static KoboDeviceDescriptor getKoboDeviceDescriptorStatic();
static void enableWiFiConnectionStatic();
static void disableWiFiConnectionStatic();
static bool testInternetConnectionStatic(int timeout);
KoboDeviceDescriptor koboDevice;
KoboWifiManager wifiManager;
QStringList m_paramList;
KoboFbScreen *m_primaryScreen;
QPlatformInputContext *m_inputContext;
QScopedPointer<QPlatformFontDatabase> m_fontDb;
QScopedPointer<QPlatformServices> m_services;
QEvdevKeyboardManager *m_kbdMgr;
KoboButtonIntegration *koboKeyboard;
KoboPlatformAdditions *koboAdditions;
bool debug;
};
#endif // QLINUXFBINTEGRATION_H
| 2,529
|
C++
|
.h
| 56
| 41.178571
| 92
| 0.821516
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,777
|
qevdevtouchhandler.h
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchhandler.h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QEVDEVTOUCHHANDLER_H
#define QEVDEVTOUCHHANDLER_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/private/qthread_p.h>
#include <qpa/qwindowsysteminterface.h>
#include <QList>
#include <QObject>
#include <QString>
#include <QThread>
#include "kobofbscreen.h"
QT_BEGIN_NAMESPACE
class QSocketNotifier;
class QEvdevTouchScreenData;
class QEvdevTouchScreenHandler : public QObject
{
Q_OBJECT
public:
explicit QEvdevTouchScreenHandler(const QString &device, const QString &spec,
QObject *parent, KoboFbScreen *koboFbScreen);
~QEvdevTouchScreenHandler();
QTouchDevice *touchDevice() const;
bool isFiltered() const;
void readData();
signals:
void touchPointsUpdated();
private:
friend class QEvdevTouchScreenData;
friend class QEvdevTouchScreenHandlerThread;
void registerTouchDevice();
void unregisterTouchDevice();
QSocketNotifier *m_notify;
int m_fd;
QEvdevTouchScreenData *d;
QTouchDevice *m_device;
};
QT_END_NAMESPACE
#endif // QEVDEVTOUCH_P_H
| 3,276
|
C++
|
.h
| 85
| 36.188235
| 83
| 0.721802
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,778
|
einkenums.h
|
Rain92_qt5-kobo-platform-plugin/src/einkenums.h
|
#ifndef EINKENUMS_H
#define EINKENUMS_H
#include <QtCore>
enum KoboKey
{
Key_Light = Qt::Key_BrightnessAdjust,
Key_Home = Qt::Key_Home,
Key_Power = Qt::Key_PowerDown,
Key_SleepCover = Qt::Key_PowerOff + 10000,
Key_PagePackward = Qt::Key_PageUp,
Key_PageForward = Qt::Key_PageDown,
Key_Eraser = 0x01010001,
Key_Highlighter = 0x01010002
};
static const QMap<int, KoboKey> KoboPhysicalKeyMap = {
{35, Key_SleepCover}, {59, Key_SleepCover}, {90, Key_Light},
{102, Key_Home}, {116, Key_Power}, {193, Key_PagePackward},
{194, Key_PageForward}, {331, Key_Eraser}, {332, Key_Highlighter},
};
enum ScreenRotation
{
RotationUR = 0,
RotationCW = 1,
RotationUD = 2,
RotationCCW = 3
};
enum WaveForm
{
WaveForm_AUTO = 257,
// Let the EPDC choose, via histogram analysis of the refresh region.
// May *not* always (or ever) opt to use REAGL on devices where it is otherwise
// available. This is the default. If you request a flashing update w/ AUTO, FBInk
// automatically uses GC16 instead.
// Common
WaveForm_DU = 1,
// From any to B&W, fast (~260ms), some light ghosting.
// On-screen pixels will be left as-is for new content that is *not* B&W.
// Great for UI highlights, or tracing touch/pen input.
// Will never flash.
// DU stands for "Direct Update".
WaveForm_GC16 = 2,
// From any to any, ~450ms, high fidelity (i.e., lowest risk of ghosting).
// Ideal for image content.
// If flashing, will flash and update the full region.
// If not, only changed pixels will update.
// GC stands for "Grayscale Clearing"
WaveForm_GC4 = 3,
// From any to B/W/GRAYA/GRAY5, (~290ms), some ghosting. (may be implemented as DU4 on some devices).
// Will *probably* never flash, especially if the device doesn't implement any other 4 color
// modes. Limited use-cases in practice.
WaveForm_A2 = 4,
// From B&W to B&W, fast (~120ms), some ghosting.
// On-screen pixels will be left as-is for new content that is *not* B&W.
// FBInk will ask the EPDC to enforce quantization to B&W to honor the "to" requirement,
// (via EPDC_FLAG_FORCE_MONOCHROME).
// Will never flash.
// Consider bracketing a series of A2 refreshes between white screens to transition in and out
// of A2, so as to honor the "from" requirement, (especially given that FORCE_MONOCHROME may
// not be reliably able to do so, c.f., refresh_kobo_mk7): non-flashing GC16 for the in
// transition, A2 or GC16 for the out transition. A stands for "Animation"
WaveForm_GL16 = 5,
// From white to any, ~450ms, some ghosting.
// Typically optimized for text on a white background.
// Newer generation devices only
WaveForm_REAGL = 6,
// From white to any, ~450ms, with ghosting and flashing reduction.
// When available, best option for text (in place of GL16).
// May enforce timing constraints if in collision with another waveform mode, e.g.,
// it may, to some extent, wait for completion of previous updates to have access to HW
// resources. Marketing term for the feature is "Regal". Technically called 5-bit waveform
// modes.
WaveForm_REAGLD = 7
// From white to any, ~450ms, with more ghosting reduction, but less flashing reduction.
// Should only be used when flashing, which should yield a less noticeable flash than GC16.
// Rarely used in practice, because still optimized for text or lightly mixed content,
// not pure image content.
};
#endif // EINKENUMS_H
| 3,587
|
C++
|
.h
| 78
| 41.679487
| 105
| 0.690551
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,779
|
qevdevtouchdata.h
|
Rain92_qt5-kobo-platform-plugin/src/qevdevtouchdata.h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2016 Jolla Ltd, author: <gunnar.sletta@jollamobile.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QEVDEVTOUCHDATA_H
#define QEVDEVTOUCHDATA_H
#include <linux/input.h>
#include <qpa/qwindowsysteminterface.h>
#include "qevdevtouchfilter_p.h"
#define ABS_MT_SLOT 0x2f
QT_BEGIN_NAMESPACE
class QEvdevTouchScreenHandler;
class QEvdevTouchScreenData
{
public:
QEvdevTouchScreenData(QEvdevTouchScreenHandler *q_ptr, const QStringList &args);
virtual QPointF transformTouchPoint(const QPointF &p);
virtual void processInputEvent(input_event *data);
void assignIds();
QEvdevTouchScreenHandler *q;
int m_lastEventType;
QList<QWindowSystemInterface::TouchPoint> m_touchPoints;
QList<QWindowSystemInterface::TouchPoint> m_lastTouchPoints;
enum Tool
{
UNKNOWN_TOOL,
FINGER,
PEN,
};
struct Contact
{
int trackingId = -1;
int x = -1;
int y = -1;
int maj = -1;
int pressure = 0;
Qt::TouchPointState state = Qt::TouchPointPressed;
QTouchEvent::TouchPoint::InfoFlags flags;
Tool tool;
};
QHash<int, Contact> m_contacts; // The key is a tracking id for type A, slot number for type B.
QHash<int, Contact> m_lastContacts;
Contact m_currentData;
int m_currentSlot;
double m_timeStamp;
double m_lastTimeStamp;
int findClosestContact(const QHash<int, Contact> &contacts, int x, int y, int *dist);
virtual void addTouchPoint(const Contact &contact, Qt::TouchPointStates *combinedStates);
void reportPoints();
void loadMultiScreenMappings();
QRect screenGeometry() const;
void setScreenGeometry(QRect rect);
int hw_range_x_min;
int hw_range_x_max;
int hw_range_y_min;
int hw_range_y_max;
int hw_pressure_min;
int hw_pressure_max;
QString hw_name;
QString deviceNode;
bool m_forceToActiveWindow;
bool m_typeB;
int m_swapXY;
bool m_invertX;
bool m_invertY;
int m_rotate;
bool m_singleTouch;
bool m_btnTool;
QString m_screenName;
QRect m_screenGeometry;
// Touch filtering and prediction are part of the same thing. The default
// prediction is 0ms, but sensible results can be achieved by setting it
// to, for instance, 16ms.
// For filtering to work well, the QPA plugin should provide a dead-steady
// implementation of QPlatformWindow::requestUpdate().
bool m_filtered;
int m_prediction;
// When filtering is enabled, protect the access to current and last
// timeStamp and touchPoints, as these are being read on the gui thread.
QMutex m_mutex;
};
QT_END_NAMESPACE
#endif // QEVDEVTOUCH_P_H
| 4,598
|
C++
|
.h
| 118
| 35.228814
| 100
| 0.711051
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,780
|
kobofbscreen.h
|
Rain92_qt5-kobo-platform-plugin/src/kobofbscreen.h
|
#ifndef QKOBOFBSCREEN_H
#define QKOBOFBSCREEN_H
#include <QtFbSupport/private/qfbscreen_p.h>
#include <sys/ioctl.h>
#include <cstring>
#include "dither.h"
#include "eink/mxcfb-kobo.h"
#include "einkenums.h"
#include "fbink.h"
#include "kobodevicedescriptor.h"
class QPainter;
class QFbCursor;
class KoboFbScreen : public QFbScreen
{
Q_OBJECT
public:
KoboFbScreen(const QStringList &args, KoboDeviceDescriptor *koboDevice);
~KoboFbScreen();
bool initialize() override;
void setFullScreenRefreshMode(WaveForm waveform);
void clearScreen(bool waitForCompleted);
void enableDithering(bool softwareDithering, bool hardwareDithering);
void doManualRefresh(const QRect ®ion);
bool setScreenRotation(ScreenRotation r, int bpp = 8);
void doSunxiPenRefresh();
ScreenRotation getScreenRotation();
FBInkConfig *getFBInkConfig();
FBInkState *getFBInkState();
QRegion doRedraw() override;
private:
void ditherRegion(const QRect ®ion);
KoboDeviceDescriptor *koboDevice;
QStringList mArgs;
int mFbFd;
bool debug;
QImage mFbScreenImage;
int mBytesPerLine;
QImage mScreenImageDither;
QPainter *mBlitter;
FBInkState fbink_state;
struct
{
unsigned char *bufferPtr;
size_t bufferSize;
} memmapInfo;
FBInkConfig fbink_cfg;
bool waitForRefresh;
bool useHardwareDithering;
bool useSoftwareDithering;
WFM_MODE_INDEX_T waveFormFullscreen;
WFM_MODE_INDEX_T waveFormPartial;
WFM_MODE_INDEX_T waveFormFast;
int originalRotation;
int originalBpp;
};
#endif // QKOBOFBSCREEN_H
| 1,641
|
C++
|
.h
| 56
| 24.946429
| 76
| 0.757225
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,781
|
koboplatformfunctions.h
|
Rain92_qt5-kobo-platform-plugin/src/koboplatformfunctions.h
|
#ifndef KOBOPLATFORMFUNCTIONS_H
#define KOBOPLATFORMFUNCTIONS_H
#include <QRect>
#include <QtCore/QByteArray>
#include <QtGui/QGuiApplication>
#include "einkenums.h"
#include "kobodevicedescriptor.h"
class KoboPlatformFunctions
{
public:
typedef int (*getBatteryLevelType)();
static QByteArray getBatteryLevelIdentifier() { return QByteArrayLiteral("getBatteryLevel"); }
static int getBatteryLevel()
{
auto func = reinterpret_cast<getBatteryLevelType>(
QGuiApplication::platformFunction(getBatteryLevelIdentifier()));
if (func)
return func();
return 0;
}
typedef bool (*isBatteryChargingType)();
static QByteArray isBatteryChargingIdentifier() { return QByteArrayLiteral("isBatteryCharging"); }
static bool isBatteryCharging()
{
auto func = reinterpret_cast<isBatteryChargingType>(
QGuiApplication::platformFunction(isBatteryChargingIdentifier()));
if (func)
return func();
return false;
}
typedef void (*setFrontlightLevelType)(int val, int temp);
static QByteArray setFrontlightLevelIdentifier() { return QByteArrayLiteral("setFrontlightLevel"); }
static void setFrontlightLevel(int val, int temp)
{
auto func = reinterpret_cast<setFrontlightLevelType>(
QGuiApplication::platformFunction(setFrontlightLevelIdentifier()));
if (func)
func(val, temp);
}
typedef void (*setFullScreenRefreshModeType)(WaveForm waveform);
static QByteArray setFullScreenRefreshModeIdentifier()
{
return QByteArrayLiteral("setFullScreenRefreshMode");
}
static void setFullScreenRefreshMode(WaveForm waveform)
{
auto func = reinterpret_cast<setFullScreenRefreshModeType>(
QGuiApplication::platformFunction(setFullScreenRefreshModeIdentifier()));
if (func)
func(waveform);
}
typedef void (*clearScreenType)(bool waitForCompleted);
static QByteArray clearScreenIdentifier() { return QByteArrayLiteral("clearScreen"); }
static void clearScreen(bool waitForCompleted)
{
auto func =
reinterpret_cast<clearScreenType>(QGuiApplication::platformFunction(clearScreenIdentifier()));
if (func)
func(waitForCompleted);
}
typedef void (*enableDitheringType)(bool softwareDithering, bool hardwareDithering);
static QByteArray enableDitheringIdentifier() { return QByteArrayLiteral("enableDithering"); }
static void enableDithering(bool softwareDithering, bool hardwareDithering)
{
auto func = reinterpret_cast<enableDitheringType>(
QGuiApplication::platformFunction(enableDitheringIdentifier()));
if (func)
func(softwareDithering, hardwareDithering);
}
typedef void (*doManualRefreshType)(QRect region);
static QByteArray doManualRefreshIdentifier() { return QByteArrayLiteral("doManualRefresh"); }
static void doManualRefresh(QRect region)
{
auto func = reinterpret_cast<doManualRefreshType>(
QGuiApplication::platformFunction(doManualRefreshIdentifier()));
if (func)
func(region);
}
typedef KoboDeviceDescriptor (*getKoboDeviceDescriptorType)();
static QByteArray getKoboDeviceDescriptorIdentifier()
{
return QByteArrayLiteral("getKoboDeviceDescriptor");
}
static KoboDeviceDescriptor getKoboDeviceDescriptor()
{
auto func = reinterpret_cast<getKoboDeviceDescriptorType>(
QGuiApplication::platformFunction(getKoboDeviceDescriptorIdentifier()));
if (func)
return func();
return KoboDeviceDescriptor();
}
typedef bool (*testInternetConnectionType)(int timeout);
static QByteArray testInternetConnectionIdentifier()
{
return QByteArrayLiteral("testInternetConnection");
}
static bool testInternetConnection(int timeout = 2)
{
auto func = reinterpret_cast<testInternetConnectionType>(
QGuiApplication::platformFunction(testInternetConnectionIdentifier()));
if (func)
return func(timeout);
return false;
}
typedef void (*enableWiFiConnectionType)();
static QByteArray enableWiFiConnectionIdentifier() { return QByteArrayLiteral("enableWiFiConnection"); }
static void enableWiFiConnection()
{
auto func = reinterpret_cast<enableWiFiConnectionType>(
QGuiApplication::platformFunction(enableWiFiConnectionIdentifier()));
if (func)
func();
}
typedef void (*disableWiFiConnectionType)();
static QByteArray disableWiFiConnectionIdentifier() { return QByteArrayLiteral("disableWiFiConnection"); }
static void disableWiFiConnection()
{
auto func = reinterpret_cast<disableWiFiConnectionType>(
QGuiApplication::platformFunction(disableWiFiConnectionIdentifier()));
if (func)
func();
}
};
#endif // KOBOPLATFORMFUNCTIONS_H
| 5,043
|
C++
|
.h
| 124
| 33.467742
| 110
| 0.7182
|
Rain92/qt5-kobo-platform-plugin
| 32
| 7
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,782
|
main_cgal2ourres.cpp
|
c-sommer_primitect/cpp/cgal_test/main_cgal2ourres.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
Adapted and extended from CGAL Shape Detection examples
(c) 2015, Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <CGAL/number_utils.h>
#include <CGAL/property_map.h>
#include <CGAL/random_simplify_point_set.h>
#include <CLI/CLI.hpp>
#include <fstream>
#include <iostream>
// Type declarations
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT FT;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map;
typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;
// In Shape_detection_traits the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::Shape_detection_traits<Kernel,Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
typedef CGAL::Shape_detection_3::Sphere<Traits> Sphere;
typedef CGAL::Shape_detection_3::Cylinder<Traits> Cylinder;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
int SPHERE_TYPE = 1;
int PLANE_TYPE = 2;
int CYLINDER_TYPE = 3;
int CONE_TYPE = 4;
void label_type(Eigen::VectorXi& label_per_point, Eigen::VectorXi& type_per_point, int instance, int type, const std::vector<size_t>& indices) {
for (int i = 0 ; i < indices.size(); i++){
label_per_point(indices[i]) = instance;
type_per_point(indices[i]) = type;
}
}
int main(int argc, char** argv) {
// parse setttings from command line
std::string folder, infile, results, otype;
size_t num_points = 0;
CLI::App app{"Detect objects in .xyz point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .xyz format")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--type", otype, "type of object to be detected")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
enum class Object {
ALL,
PLANE,
SPHERE,
CYLINDER,
CONE,
PLANE_SPHERE,
PLANE_CYL,
PLANE_CONE
};
Object O;
if (otype == "plane") {
O = Object::PLANE;
}
else if (otype == "sphere") {
O = Object::SPHERE;
}
else if (otype == "cylinder") {
O = Object::CYLINDER;
}
else if (otype == "cone") {
O = Object::CONE;
}
else if (otype == "plane-sphere") {
O = Object::PLANE_SPHERE;
}
else if (otype == "plane-cyl") {
O = Object::PLANE_CYL;
}
else if (otype == "plane-cone") {
O = Object::PLANE_CONE;
}
else if (otype == "all") {
O = Object::ALL;
}
else {
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
// Points with normals.
Pwn_vector points;
// Measures time before loading the data.
CGAL::Timer time;
time.start();
// Loads point set from a file.
// read_xyz_points_and_normals takes an OutputIterator for storing the points
// and a property map to store the normal vector with each point.
std::ifstream stream(folder + infile);
if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()).normal_map(Normal_map()))) {
std::cerr << "Error: cannot read file" << std::endl;
return EXIT_FAILURE;
}
// Measures time after preprocessing.
time.stop();
std::cout << "loading data took: " << time.time() * 1000 << "ms" << std::endl;
if (num_points > 0) {
points.erase(CGAL::random_simplify_point_set(points, 100.*(1. - double(num_points) / double(points.size()))), points.end());
}
// Instantiates shape detection engine.
Efficient_ransac ransac;
// Provides the input data.
ransac.set_input(points);
// Registers detection of objects
switch (O) {
case Object::PLANE :
ransac.add_shape_factory<Plane>();
break;
case Object::SPHERE :
ransac.add_shape_factory<Sphere>();
break;
case Object::CYLINDER :
ransac.add_shape_factory<Cylinder>();
break;
case Object::CONE :
ransac.add_shape_factory<Cone>();
break;
case Object::PLANE_SPHERE :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Sphere>();
break;
case Object::PLANE_CYL :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Cylinder>();
break;
case Object::PLANE_CONE :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Cone>();
break;
case Object::ALL :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Sphere>();
ransac.add_shape_factory<Cylinder>();
ransac.add_shape_factory<Cone>();
break;
default:
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
// Measures time before setting up the shape detection.
time.start();
// Build internal data structures.
ransac.preprocess();
// Measures time after preprocessing.
time.stop();
std::cout << "preprocessing took: " << time.time() * 1000 << "ms" << std::endl;
// Sets parameters for shape detection.
Efficient_ransac::Parameters parameters;
// Sets probability to miss the largest primitive at each iteration. (Default: 5%)
// parameters.probability = 0.05;
// Set minimium number of points that a shape must contain. (Default: 1% of points)
// parameters.min_points = 200;
// Sets maximum Euclidean distance between a point and a shape. (Default: 1% of BB diagonal)
parameters.epsilon = 0.05;
// Sets maximum Euclidean distance between points to be clustered. (Default: 1% of BB diagonal)
// parameters.cluster_epsilon = 0.01;
// Sets maximum normal deviation as cos of surface normal and point normal. (Default: .9 = cos(25.8°))
// 0.9 < dot(surface_normal, point_normal);
parameters.normal_threshold = std::cos(10. * M_PI / 180.);
// Perform detection several times and choose result with highest coverage.
Efficient_ransac::Shape_range shapes = ransac.shapes();
FT best_coverage = 0;
for (size_t i = 0; i < 1; i++) {
// Reset timer.
time.reset();
time.start();
// Detects shapes.
ransac.detect(parameters);
// Measures time after detection.
time.stop();
// Compute coverage, i.e. ratio of the points assigned to a shape.
FT coverage = FT(points.size() - ransac.number_of_unassigned_points())
/ FT(points.size());
// Prints number of assigned shapes and unsassigned points.
std::cout << "time: " << time.time() * 1000 << "ms" << std::endl;
std::cout << ransac.shapes().end() - ransac.shapes().begin() << " primitives, "
<< coverage << " coverage" << std::endl;
// Choose result with highest coverage.
if (coverage > best_coverage) {
best_coverage = coverage;
// Efficient_ransac::shapes() provides
// an iterator range to the detected shapes.
shapes = ransac.shapes();
}
}
std::cout<<"number of instances: "<<shapes.size()<<std::endl;
std::cout<<"point size N = "<<points.size()<<std::endl;
Eigen::VectorXi label_per_point(points.size());
label_per_point.setZero();
Eigen::VectorXi type_per_point(points.size());
type_per_point.setZero();
std::string prefix = infile.substr(0, infile.size()-4);
std::cout<<"file prefix: "<<prefix<<std::endl;
std::ofstream labelsFile(results + prefix + "_points_with_labels.txt");
if ( !labelsFile.is_open() ) {
std::cout<<"label not open...\n";
return -1;
}
std::ofstream planesFile(results + prefix + "_planes.txt");
if ( !planesFile.is_open() ) {
std::cout<<"plane not open...\n";
return -1;
}
std::ofstream spheresFile(results + prefix + "_spheres.txt");
if ( !spheresFile.is_open() ) {
std::cout<<"sphere not open...\n";
return -1;
}
std::ofstream cylindersFile(results + prefix + "_cylinders.txt");
if ( !cylindersFile.is_open() ) {
std::cout<<"cylinder not open...\n";
return -1;
}
std::ofstream conesFile(results + prefix + "_cones.txt");
if ( !conesFile.is_open() ) {
std::cout<<"cone not open...\n";
return -1;
}
int instance = 1;
int type = 0;
for (Efficient_ransac::Shape_range::iterator it = shapes.begin(); it != shapes.end(); it++) {
if (Plane* plane = dynamic_cast<Plane*>(it->get()))
{
planesFile << instance << " " << plane->plane_normal() << " " << plane->d() << std::endl;
type = 2;
}
else if (Cylinder* cyl = dynamic_cast<Cylinder*>(it->get()))
{
cylindersFile<<instance << " " << cyl->axis().point() << " " << cyl->axis().direction() << " " << cyl->radius() << std::endl;
type = 3;
}
else if (Sphere* sph = dynamic_cast<Sphere*>(it->get()))
{
spheresFile << instance << " " << sph->center() << " " << sph->radius() << std::endl;
type = 1;
}
else if (Cone* con = dynamic_cast<Cone*>(it->get()))
{
conesFile << instance << " " << con->apex() << " " << con->axis() << " " << con->angle() << std::endl;
type = 4;
}
else
{
std::cout << (*it)->info() << std::endl;
}
// Iterates through point indices assigned to each detected shape.
for (auto index_it = (*it)->indices_of_assigned_points().begin(); index_it != (*it)->indices_of_assigned_points().end(); index_it++) {
// Retrieves point
const Point_with_normal &p = *(points.begin() + (*index_it));
// write point and label to file
labelsFile << p.first.x() << " " << p.first.y() << " " << p.first.z() << " " << instance << " " << type << std::endl;
}
instance++;
}
labelsFile.close();
planesFile.close();
spheresFile.close();
cylindersFile.close();
conesFile.close();
return EXIT_SUCCESS;
}
| 11,282
|
C++
|
.cpp
| 292
| 34.558219
| 145
| 0.662492
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,783
|
main_cgal_write_points.cpp
|
c-sommer_primitect/cpp/cgal_test/main_cgal_write_points.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
Adapted and extended from CGAL Shape Detection examples
(c) 2015, Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <CGAL/number_utils.h>
#include <CGAL/property_map.h>
#include <CLI/CLI.hpp>
#include <fstream>
#include <iostream>
// Type declarations
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT FT;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map;
typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;
// In Shape_detection_traits the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::Shape_detection_traits<Kernel,Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
typedef CGAL::Shape_detection_3::Sphere<Traits> Sphere;
typedef CGAL::Shape_detection_3::Cylinder<Traits> Cylinder;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
int SPHERE_TYPE = 1;
int PLANE_TYPE = 2;
int CYLINDER_TYPE = 3;
int CONE_TYPE = 4;
std::string IntToStr(int a) {
std::stringstream ss;
ss << a;
return ss.str();
}
void write_points(std::string filename, const Pwn_vector& points, const std::vector<size_t>& indices) {
std::ofstream pointsFile(filename);
if ( !pointsFile.is_open() ) {
std::cout<<"points file not open...\n";
return;
}
for (int i = 0 ; i <indices.size(); i++){
pointsFile<<points[indices[i]].first<<","<<points[indices[i]].second<<std::endl;
}
pointsFile.close();
}
int main(int argc, char** argv) {
// parse setttings from command line
std::string folder, infile, results, otype;
CLI::App app{"Detect objects in .xyz point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .xyz format")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--type", otype, "type of object to be detected")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
enum class Object {
ALL,
PLANE,
SPHERE,
CYLINDER,
CONE,
PLANE_SPHERE,
PLANE_CYL,
PLANE_CONE
};
Object O;
if (otype == "plane") {
O = Object::PLANE;
}
else if (otype == "sphere") {
O = Object::SPHERE;
}
else if (otype == "cylinder") {
O = Object::CYLINDER;
}
else if (otype == "cone") {
O = Object::CONE;
}
else if (otype == "plane-sphere") {
O = Object::PLANE_SPHERE;
}
else if (otype == "plane-cyl") {
O = Object::PLANE_CYL;
}
else if (otype == "plane-cone") {
O = Object::PLANE_CONE;
}
else if (otype == "all") {
O = Object::ALL;
}
else {
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
// Points with normals.
Pwn_vector points;
// Measures time before loading the data.
CGAL::Timer time;
time.start();
// Loads point set from a file.
// read_xyz_points_and_normals takes an OutputIterator for storing the points
// and a property map to store the normal vector with each point.
std::ifstream stream(folder + infile);
if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()).normal_map(Normal_map()))) {
std::cerr << "Error: cannot read file" << std::endl;
return EXIT_FAILURE;
}
// Measures time after preprocessing.
time.stop();
std::cout << "loading data took: " << time.time() * 1000 << "ms" << std::endl;
// Instantiates shape detection engine.
Efficient_ransac ransac;
// Provides the input data.
ransac.set_input(points);
// Registers detection of objects
switch (O) {
case Object::PLANE :
ransac.add_shape_factory<Plane>();
break;
case Object::SPHERE :
ransac.add_shape_factory<Sphere>();
break;
case Object::CYLINDER :
ransac.add_shape_factory<Cylinder>();
break;
case Object::CONE :
ransac.add_shape_factory<Cone>();
break;
case Object::PLANE_SPHERE :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Sphere>();
break;
case Object::PLANE_CYL :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Cylinder>();
break;
case Object::PLANE_CONE :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Cone>();
break;
case Object::ALL :
ransac.add_shape_factory<Plane>();
ransac.add_shape_factory<Sphere>();
ransac.add_shape_factory<Cylinder>();
ransac.add_shape_factory<Cone>();
break;
default:
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
// Measures time before setting up the shape detection.
time.start();
// Build internal data structures.
ransac.preprocess();
// Measures time after preprocessing.
time.stop();
std::cout << "preprocessing took: " << time.time() * 1000 << "ms" << std::endl;
// Sets parameters for shape detection.
Efficient_ransac::Parameters parameters;
// Sets probability to miss the largest primitive at each iteration. (Default: 5%)
// parameters.probability = 0.05;
// Set minimium number of points that a shape must contain. (Default: 1% of points)
// parameters.min_points = 200;
// Sets maximum Euclidean distance between a point and a shape. (Default: 1% of BB diagonal)
parameters.epsilon = 0.05;
// Sets maximum Euclidean distance between points to be clustered. (Default: 1% of BB diagonal)
// parameters.cluster_epsilon = 0.01;
// Sets maximum normal deviation as cos of surface normal and point normal. (Default: .9 = cos(25.8°))
// 0.9 < dot(surface_normal, point_normal);
parameters.normal_threshold = std::cos(10. * M_PI / 180.);
// Perform detection several times and choose result with highest coverage.
Efficient_ransac::Shape_range shapes = ransac.shapes();
FT best_coverage = 0;
for (size_t i = 0; i < 3; i++) {
// Reset timer.
time.reset();
time.start();
// Detects shapes.
ransac.detect(parameters);
// Measures time after detection.
time.stop();
// Compute coverage, i.e. ratio of the points assigned to a shape.
FT coverage = FT(points.size() - ransac.number_of_unassigned_points())
/ FT(points.size());
// Prints number of assigned shapes and unsassigned points.
std::cout << "time: " << time.time() * 1000 << "ms" << std::endl;
std::cout << ransac.shapes().end() - ransac.shapes().begin() << " primitives, "
<< coverage << " coverage" << std::endl;
// Choose result with highest coverage.
if (coverage > best_coverage) {
best_coverage = coverage;
// Efficient_ransac::shapes() provides
// an iterator range to the detected shapes.
shapes = ransac.shapes();
}
}
std::cout<<"number of instances: "<<shapes.size()<<std::endl;
std::cout<<"point size N = "<<points.size()<<std::endl;
std::string prefix = infile.substr(0, infile.size()-4);
std::cout<<"file prefix: "<<prefix<<std::endl;
int instance = 0;
for (Efficient_ransac::Shape_range::iterator it = shapes.begin(); it != shapes.end(); it++) {
if (Cylinder* cyl = dynamic_cast<Cylinder*>(it->get()))
{
std::string name = results+prefix+"cylinder_"+IntToStr(instance)+"_points.txt";
write_points(name, points, cyl->indices_of_assigned_points());
}
else if (Sphere* sph = dynamic_cast<Sphere*>(it->get()))
{
std::string name = results+prefix+"sphere_"+IntToStr(instance)+"_points.txt";
write_points(name, points, sph->indices_of_assigned_points());
}
else if (Cone* con = dynamic_cast<Cone*>(it->get()))
{
std::string name = results+prefix+"cone_"+IntToStr(instance)+"_points.txt";
write_points(name, points, con->indices_of_assigned_points());
}
else
{
std::cout << (*it)->info() << std::endl;
}
instance++;
}
return EXIT_SUCCESS;
}
| 9,493
|
C++
|
.cpp
| 249
| 34.216867
| 145
| 0.682998
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,784
|
PointCloudData.cpp
|
c-sommer_primitect/cpp/include/pcd/PointCloudData.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "PointCloudData.h"
#include <fstream>
#include <tinyply/tinyply.h>
PointCloudData::PointCloudData(std::string filepath) {
try {
std::ifstream ss(filepath, std::ios::binary);
if (ss.fail())
throw std::runtime_error("failed to open " + filepath);
tinyply::PlyFile file;
file.parse_header(ss);
// Tinyply treats parsed data as untyped byte buffers. See below for examples.
std::shared_ptr<tinyply::PlyData> points, normals;
try {
points = file.request_properties_from_element("vertex", { "x", "y", "z" });
} catch (const std::exception & e) {
std::cerr << "tinyply exception: " << e.what() << std::endl;
}
try {
normals = file.request_properties_from_element("vertex", { "nx", "ny", "nz" });
} catch (const std::exception & e) {
std::cerr << "tinyply exception: " << e.what() << std::endl;
}
file.read(ss);
// type casting to your own native types
points_ = std::vector<Eigen::Vector3f>(points->count);
std::memcpy(points_.data(), points->buffer.get(), points->buffer.size_bytes());
normals_ = std::vector<Eigen::Vector3f>(normals->count);
std::memcpy(normals_.data(), normals->buffer.get(), normals->buffer.size_bytes());
num_points_ = points_.size();
} catch (const std::exception & e) {
std::cerr << "Caught tinyply exception: " << e.what() << std::endl;
}
normalize();
}
void PointCloudData::write(std::string filepath) {
std::filebuf fb_binary;
fb_binary.open(filepath, std::ios::out | std::ios::binary);
std::ostream outstream_binary(&fb_binary);
if (outstream_binary.fail())
throw std::runtime_error("failed to open " + filepath);
tinyply::PlyFile ply_file;
ply_file.add_properties_to_element("vertex", { "x", "y", "z" }, tinyply::Type::FLOAT32, num_points_, reinterpret_cast<uint8_t*>(points_.data()), tinyply::Type::INVALID, 0);
ply_file.add_properties_to_element("vertex", { "nx", "ny", "nz" }, tinyply::Type::FLOAT32, num_points_, reinterpret_cast<uint8_t*>(normals_.data()), tinyply::Type::INVALID, 0);
ply_file.write(outstream_binary, true);
}
| 3,055
|
C++
|
.cpp
| 64
| 44.703125
| 180
| 0.711104
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,785
|
main_track_cylinder_ransac.cpp
|
c-sommer_primitect/cpp/track_object/main_track_cylinder_ransac.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
Adapted and extended from CGAL Shape Detection examples
(c) 2015, Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <CGAL/number_utils.h>
#include <CGAL/property_map.h>
#include <CGAL/random_simplify_point_set.h>
#include <CLI/CLI.hpp>
#include <fstream>
#include <iostream>
// Type declarations
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT FT;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map;
typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;
// In Shape_detection_traits the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::Shape_detection_traits<Kernel,Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
typedef CGAL::Shape_detection_3::Sphere<Traits> Sphere;
typedef CGAL::Shape_detection_3::Cylinder<Traits> Cylinder;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
int SPHERE_TYPE = 1;
int PLANE_TYPE = 2;
int CYLINDER_TYPE = 3;
int CONE_TYPE = 4;
void label_type(Eigen::VectorXi& label_per_point, Eigen::VectorXi& type_per_point, int instance, int type, const std::vector<size_t>& indices) {
for (int i = 0 ; i < indices.size(); i++){
label_per_point(indices[i]) = instance;
type_per_point(indices[i]) = type;
}
}
int main(int argc, char** argv) {
std::string folder, results, pc_file;
std::string otype = "cylinder";
size_t num_points = 2048;
CLI::App app{"Track sphere in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
// Points with normals.
Pwn_vector points;
// Sets parameters for shape detection.
Efficient_ransac::Parameters parameters;
// Sets probability to miss the largest primitive at each iteration. (Default: 5%)
// parameters.probability = 0.05;
// Set minimium number of points that a shape must contain. (Default: 1% of points)
// parameters.min_points = 200;
// Sets maximum Euclidean distance between a point and a shape. (Default: 1% of BB diagonal)
parameters.epsilon = 0.05;
// Sets maximum Euclidean distance between points to be clustered. (Default: 1% of BB diagonal)
// parameters.cluster_epsilon = 0.01;
// Sets maximum normal deviation as cos of surface normal and point normal. (Default: .9 = cos(25.8°))
// 0.9 < dot(surface_normal, point_normal);
parameters.normal_threshold = std::cos(10. * M_PI / 180.);
std::ifstream infile(folder + "files_xyz.txt");
std::ofstream outfile(results + "cylinders.txt");
while (!infile.eof()) {
infile >> pc_file;
// Loads point set from a file.
// read_xyz_points_and_normals takes an OutputIterator for storing the points
// and a property map to store the normal vector with each point.
std::ifstream stream(folder + pc_file);
if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()).normal_map(Normal_map()))) {
std::cerr << "Error: cannot read file" << std::endl;
return EXIT_FAILURE;
}
if (num_points > 0) {
points.erase(CGAL::random_simplify_point_set(points, 100.*(1. - double(num_points) / double(points.size()))), points.end());
}
// Instantiates shape detection engine.
Efficient_ransac ransac;
// Provides the input data.
ransac.set_input(points);
// Registers detection of objects
ransac.add_shape_factory<Cylinder>();
// Build internal data structures.
ransac.preprocess();
// Perform detection
Efficient_ransac::Shape_range shapes = ransac.shapes();
ransac.detect(parameters);
shapes = ransac.shapes();
// Write first detection to file
Efficient_ransac::Shape_range::iterator it = shapes.begin();
Cylinder* cyl = dynamic_cast<Cylinder*>(it->get());
outfile << cyl->axis().point() << " " << cyl->axis().direction() << " " << cyl->radius() << std::endl;
}
infile.close();
outfile.close();
return EXIT_SUCCESS;
}
| 5,890
|
C++
|
.cpp
| 121
| 44.190083
| 151
| 0.708989
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,786
|
main_track_sphere_ransac.cpp
|
c-sommer_primitect/cpp/track_object/main_track_sphere_ransac.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
Adapted and extended from CGAL Shape Detection examples
(c) 2015, Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <CGAL/number_utils.h>
#include <CGAL/property_map.h>
#include <CGAL/random_simplify_point_set.h>
#include <CLI/CLI.hpp>
#include <fstream>
#include <iostream>
// Type declarations
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT FT;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map;
typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;
// In Shape_detection_traits the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::Shape_detection_traits<Kernel,Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
typedef CGAL::Shape_detection_3::Sphere<Traits> Sphere;
typedef CGAL::Shape_detection_3::Cylinder<Traits> Cylinder;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
int SPHERE_TYPE = 1;
int PLANE_TYPE = 2;
int CYLINDER_TYPE = 3;
int CONE_TYPE = 4;
void label_type(Eigen::VectorXi& label_per_point, Eigen::VectorXi& type_per_point, int instance, int type, const std::vector<size_t>& indices) {
for (int i = 0 ; i < indices.size(); i++){
label_per_point(indices[i]) = instance;
type_per_point(indices[i]) = type;
}
}
int main(int argc, char** argv) {
std::string folder, results, pc_file;
std::string otype = "sphere";
size_t num_points = 2048;
CLI::App app{"Track sphere in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
// Points with normals.
Pwn_vector points;
// Sets parameters for shape detection.
Efficient_ransac::Parameters parameters;
// Sets probability to miss the largest primitive at each iteration. (Default: 5%)
// parameters.probability = 0.05;
// Set minimium number of points that a shape must contain. (Default: 1% of points)
// parameters.min_points = 200;
// Sets maximum Euclidean distance between a point and a shape. (Default: 1% of BB diagonal)
parameters.epsilon = 0.05;
// Sets maximum Euclidean distance between points to be clustered. (Default: 1% of BB diagonal)
// parameters.cluster_epsilon = 0.01;
// Sets maximum normal deviation as cos of surface normal and point normal. (Default: .9 = cos(25.8°))
// 0.9 < dot(surface_normal, point_normal);
parameters.normal_threshold = std::cos(10. * M_PI / 180.);
std::ifstream infile(folder + "files_xyz.txt");
std::ofstream outfile(results + "spheres.txt");
while (!infile.eof()) {
infile >> pc_file;
// Loads point set from a file.
// read_xyz_points_and_normals takes an OutputIterator for storing the points
// and a property map to store the normal vector with each point.
std::ifstream stream(folder + pc_file);
if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()).normal_map(Normal_map()))) {
std::cerr << "Error: cannot read file" << std::endl;
return EXIT_FAILURE;
}
if (num_points > 0) {
points.erase(CGAL::random_simplify_point_set(points, 100.*(1. - double(num_points) / double(points.size()))), points.end());
}
// Instantiates shape detection engine.
Efficient_ransac ransac;
// Provides the input data.
ransac.set_input(points);
// Registers detection of objects
ransac.add_shape_factory<Sphere>();
// Build internal data structures.
ransac.preprocess();
// Perform detection
Efficient_ransac::Shape_range shapes = ransac.shapes();
ransac.detect(parameters);
shapes = ransac.shapes();
// Write first detection to file
Efficient_ransac::Shape_range::iterator it = shapes.begin();
Sphere* sph = dynamic_cast<Sphere*>(it->get());
outfile << sph->center() << " " << sph->radius() << std::endl;
}
infile.close();
outfile.close();
return EXIT_SUCCESS;
}
| 5,840
|
C++
|
.cpp
| 121
| 43.77686
| 151
| 0.710127
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,787
|
main_track_cone_ransac.cpp
|
c-sommer_primitect/cpp/track_object/main_track_cone_ransac.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
Adapted and extended from CGAL Shape Detection examples
(c) 2015, Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/IO/read_xyz_points.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Shape_detection_3.h>
#include <CGAL/Timer.h>
#include <CGAL/number_utils.h>
#include <CGAL/property_map.h>
#include <CGAL/random_simplify_point_set.h>
#include <CLI/CLI.hpp>
#include <fstream>
#include <iostream>
// Type declarations
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef Kernel::FT FT;
typedef std::pair<Kernel::Point_3, Kernel::Vector_3> Point_with_normal;
typedef std::vector<Point_with_normal> Pwn_vector;
typedef CGAL::First_of_pair_property_map<Point_with_normal> Point_map;
typedef CGAL::Second_of_pair_property_map<Point_with_normal> Normal_map;
// In Shape_detection_traits the basic types, i.e., Point and Vector types
// as well as iterator type and property maps, are defined.
typedef CGAL::Shape_detection_3::Shape_detection_traits<Kernel,Pwn_vector, Point_map, Normal_map> Traits;
typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Efficient_ransac;
typedef CGAL::Shape_detection_3::Plane<Traits> Plane;
typedef CGAL::Shape_detection_3::Sphere<Traits> Sphere;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
typedef CGAL::Shape_detection_3::Cone<Traits> Cone;
int SPHERE_TYPE = 1;
int PLANE_TYPE = 2;
int Cone_TYPE = 3;
int CONE_TYPE = 4;
void label_type(Eigen::VectorXi& label_per_point, Eigen::VectorXi& type_per_point, int instance, int type, const std::vector<size_t>& indices) {
for (int i = 0 ; i < indices.size(); i++){
label_per_point(indices[i]) = instance;
type_per_point(indices[i]) = type;
}
}
int main(int argc, char** argv) {
std::string folder, results, pc_file;
std::string otype = "cone";
size_t num_points = 2048;
CLI::App app{"Track sphere in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
// Points with normals.
Pwn_vector points;
// Sets parameters for shape detection.
Efficient_ransac::Parameters parameters;
// Sets probability to miss the largest primitive at each iteration. (Default: 5%)
// parameters.probability = 0.05;
// Set minimium number of points that a shape must contain. (Default: 1% of points)
// parameters.min_points = 200;
// Sets maximum Euclidean distance between a point and a shape. (Default: 1% of BB diagonal)
parameters.epsilon = 0.05;
// Sets maximum Euclidean distance between points to be clustered. (Default: 1% of BB diagonal)
// parameters.cluster_epsilon = 0.01;
// Sets maximum normal deviation as cos of surface normal and point normal. (Default: .9 = cos(25.8°))
// 0.9 < dot(surface_normal, point_normal);
parameters.normal_threshold = std::cos(10. * M_PI / 180.);
std::ifstream infile(folder + "files_xyz.txt");
std::ofstream outfile(results + "cones.txt");
while (!infile.eof()) {
infile >> pc_file;
// Loads point set from a file.
// read_xyz_points_and_normals takes an OutputIterator for storing the points
// and a property map to store the normal vector with each point.
std::ifstream stream(folder + pc_file);
if (!stream || !CGAL::read_xyz_points(stream, std::back_inserter(points), CGAL::parameters::point_map(Point_map()).normal_map(Normal_map()))) {
std::cerr << "Error: cannot read file" << std::endl;
return EXIT_FAILURE;
}
if (num_points > 0) {
points.erase(CGAL::random_simplify_point_set(points, 100.*(1. - double(num_points) / double(points.size()))), points.end());
}
// Instantiates shape detection engine.
Efficient_ransac ransac;
// Provides the input data.
ransac.set_input(points);
// Registers detection of objects
ransac.add_shape_factory<Cone>();
// Build internal data structures.
ransac.preprocess();
// Perform detection
Efficient_ransac::Shape_range shapes = ransac.shapes();
ransac.detect(parameters);
shapes = ransac.shapes();
// Write first detection to file
Efficient_ransac::Shape_range::iterator it = shapes.begin();
Cone* cone = dynamic_cast<Cone*>(it->get());
outfile << cone->apex() << " " << cone->axis() << " " << cone->angle() << std::endl;
}
infile.close();
outfile.close();
return EXIT_SUCCESS;
}
| 5,841
|
C++
|
.cpp
| 121
| 43.785124
| 151
| 0.707532
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,788
|
main_track_cone.cpp
|
c-sommer_primitect/cpp/track_object/main_track_cone.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "sampling/PcSampler.hpp"
#include "detector/ConeDetector.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, results, pc_file;
std::string otype = "cone";
size_t num_points = 2048, s = 39;
CLI::App app{"Track cone in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
app.add_option("--settings", s, "settings");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::bitset<6> options(s);
DetectorSettings settings(options);
std::cout << std::endl << ".........." << std::endl;
settings.print();
std::cout << std::endl;
PpfDetector<PointCloudData, float, float>* detector;
std::ifstream infile(folder + "files.txt");
std::ofstream outfile(results + "cones.txt");
while (!infile.eof()) {
infile >> pc_file;
PointCloudData pc(folder + pc_file);
PcSampler<PointCloudData, float> pcs;
std::vector<size_t> idx = pcs.sample_random(pc, num_points);
pc.sample(idx);
detector = new ConeDetector<PointCloudData, float, float>(pc.diameter(), 1, settings);
detector->cast_votes(pc);
detector->cluster_candidates();
detector->cluster_candidates();
// TODO: only write first candidate to list!
std::vector<MyObject<float>*> candidates = detector->candidate_vector(12, .35*num_points);
Cone<float>* cone = dynamic_cast<Cone<float>*>(candidates[0]);
outfile << *cone << std::endl;
}
infile.close();
outfile.close();
delete detector;
return 0;
}
| 3,061
|
C++
|
.cpp
| 71
| 37.591549
| 101
| 0.695172
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,789
|
main_track_sphere.cpp
|
c-sommer_primitect/cpp/track_object/main_track_sphere.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "sampling/PcSampler.hpp"
#include "detector/SphereDetector.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, results, pc_file;
std::string otype = "sphere";
size_t num_points = 2048, s = 39;
CLI::App app{"Track sphere in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
app.add_option("--settings", s, "settings");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::bitset<6> options(s);
DetectorSettings settings(options);
std::cout << std::endl << ".........." << std::endl;
settings.print();
std::cout << std::endl;
PpfDetector<PointCloudData, float, float>* detector;
std::ifstream infile(folder + "files.txt");
std::ofstream outfile(results + "spheres.txt");
while (!infile.eof()) {
infile >> pc_file;
PointCloudData pc(folder + pc_file);
PcSampler<PointCloudData, float> pcs;
std::vector<size_t> idx = pcs.sample_random(pc, num_points);
pc.sample(idx);
detector = new SphereDetector<PointCloudData, float, float>(pc.diameter(), 1, settings);
detector->cast_votes(pc);
detector->cluster_candidates();
detector->cluster_candidates();
// TODO: only write first candidate to list!
std::vector<MyObject<float>*> candidates = detector->candidate_vector(12, .35*num_points);
if (candidates.size() > 0) {
Sphere<float>* sphere = dynamic_cast<Sphere<float>*>(candidates[0]);
outfile << *sphere << std::endl;
}
else {
outfile << "0 0 0 0" << std::endl;
}
}
infile.close();
outfile.close();
delete detector;
return 0;
}
| 3,206
|
C++
|
.cpp
| 76
| 36.276316
| 101
| 0.681908
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,790
|
main_track_cylinder.cpp
|
c-sommer_primitect/cpp/track_object/main_track_cylinder.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "sampling/PcSampler.hpp"
#include "detector/CylinderDetector.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, results, pc_file;
std::string otype = "Cylinder";
size_t num_points = 2048, s = 39;
CLI::App app{"Track Cylinder in .ply point clouds"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--np", num_points, "number of input points to detection stage");
app.add_option("--settings", s, "settings");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::bitset<6> options(s);
DetectorSettings settings(options);
std::cout << std::endl << ".........." << std::endl;
settings.print();
std::cout << std::endl;
PpfDetector<PointCloudData, float, float>* detector;
std::ifstream infile(folder + "files.txt");
std::ofstream outfile(results + "cylinders.txt");
while (!infile.eof()) {
infile >> pc_file;
PointCloudData pc(folder + pc_file);
PcSampler<PointCloudData, float> pcs;
std::vector<size_t> idx = pcs.sample_random(pc, num_points);
pc.sample(idx);
detector = new CylinderDetector<PointCloudData, float, float>(pc.diameter(), 1, settings);
detector->cast_votes(pc);
detector->cluster_candidates();
detector->cluster_candidates();
// TODO: only write first candidate to list!
std::vector<MyObject<float>*> candidates = detector->candidate_vector(12, .35*num_points);
Cylinder<float>* cyl = dynamic_cast<Cylinder<float>*>(candidates[0]);
outfile << *cyl << std::endl;
}
infile.close();
outfile.close();
delete detector;
return 0;
}
| 3,087
|
C++
|
.cpp
| 71
| 37.957746
| 101
| 0.697881
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,791
|
main_sphere_dr.cpp
|
c-sommer_primitect/cpp/detect_objects/main_sphere_dr.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "detector/SphereDetector.h"
#include "shapefit/SphereOptimizer.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, infile;
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
DetectorSettings settings(std::bitset<6>(39));
SphereDetector<PointCloudData, float, float>* detector = new SphereDetector<PointCloudData, float, float>(settings);
SphereOptimizer<PointCloudData>* optimizer = nullptr;
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
for (auto el : detector->candidates()) {
Sphere<double> S = el.second->cast<double>();
MyObject<double>* obj = static_cast<MyObject<double>*>(&S);
std::cout << std::endl << ".......... # votes: " << el.first << std::endl;
std::cout << "Before refinement:" << std::endl;
std::cout << S << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
optimizer = new SphereOptimizer<PointCloudData>(&S);
T.tic();
bool conv = optimizer->optimize(pc);
T.toc("Parameter refinement");
if (conv) {
obj = static_cast<MyObject<double>*>(&S);
std::cout << "After refinement:" << std::endl;
std::cout << S << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
}
else {
std::cout << "No convergence." << std::endl;
}
}
delete detector;
if (optimizer) delete optimizer;
return 0;
}
| 3,190
|
C++
|
.cpp
| 77
| 35.454545
| 120
| 0.676042
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,792
|
main_voting_sample.cpp
|
c-sommer_primitect/cpp/detect_objects/main_voting_sample.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "sampling/PcSampler.hpp"
#include "detector/detectors.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, infile, results, otype;
int det_settings = 64;
size_t num_points = 4096;
bool is_scene = true, is_object = false;
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--type", otype, "type of object to be detected")->required();
app.add_option("--settings", det_settings, "int specifying DetectorSettings");
app.add_option("--np", num_points, "number of input points to detection stage");
app.add_flag("--o", is_object, "flag for object parts detection");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
if (is_object) {
is_scene = false;
}
std::vector<int> options_vec;
if (det_settings < 64) {
options_vec.push_back(det_settings);
}
else {
options_vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53};
}
enum class Object {
ALL,
PLANE,
SPHERE,
CYLINDER,
CONE,
PLANE_SPHERE,
PLANE_CYL,
PLANE_CONE
};
Object O;
if (otype == "plane") {
O = Object::PLANE;
}
else if (otype == "sphere") {
O = Object::SPHERE;
}
else if (otype == "cylinder") {
O = Object::CYLINDER;
}
else if (otype == "cone") {
O = Object::CONE;
}
else if (otype == "plane-sphere") {
O = Object::PLANE_SPHERE;
}
else if (otype == "plane-cyl") {
O = Object::PLANE_CYL;
}
else if (otype == "plane-cone") {
O = Object::PLANE_CONE;
}
else if (otype == "all") {
O = Object::ALL;
}
else {
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
std::cout << "Number of points: " << pc.num_points() << std::endl;
std::cout << "Diameter of scene: " << pc.diameter() << std::endl;
T.tic();
PcSampler<PointCloudData, float> pcs;
std::vector<size_t> idx = pcs.sample_random(pc, num_points);
pc.sample(idx);
T.toc("Downsample point cloud");
std::cout << "Number of points: " << pc.num_points() << std::endl;
std::cout << "Diameter of scene: " << pc.diameter() << std::endl;
PpfDetector<PointCloudData, float, float>* detector;
for (const int& o : options_vec) {
std::bitset<6> options(o);
DetectorSettings settings(options);
std::cout << std::endl << ".........." << std::endl;
settings.print();
std::cout << std::endl;
switch (O) {
case Object::PLANE :
detector = new PlaneDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::SPHERE :
detector = new SphereDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::CYLINDER :
detector = new CylinderDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::CONE :
detector = new ConeDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_SPHERE :
detector = new PlaneSphereDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_CYL :
detector = new PlaneCylinderDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_CONE :
detector = new PlaneConeDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::ALL :
detector = new PrimitiveDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
default:
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
detector->print_info();
// detector->print_candidates();
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
detector->print_info();
detector->print_candidates(1e3);
detector->write_results(results, infile, 12, .35*num_points);
std::cout << "# inliers, coverage, 80th percentiles, mean residuals and RMS values for candidate objects:" << std::endl;
std::vector<MyObject<float>*> candidates = detector->candidate_vector(12, .35*num_points);
for (auto& obj : candidates) {
std::cout << metric_inliers<PointCloudData, float>(pc, obj) << "\t"
<< metric_coverage<PointCloudData, float>(pc, obj)*100 << "\%\t"
<< metric_p80<PointCloudData, float>(pc, obj) << "\t"
<< metric_mean<PointCloudData, float>(pc, obj) << "\t"
<< metric_rms<PointCloudData, float>(pc, obj) << std::endl;
}
}
delete detector;
return 0;
}
| 7,020
|
C++
|
.cpp
| 169
| 33.349112
| 173
| 0.60481
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,793
|
main_refine_spheres.cpp
|
c-sommer_primitect/cpp/detect_objects/main_refine_spheres.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "shapefit/SphereOptimizer.h"
int main(int argc, char** argv) {
Timer T;
// parse setttings from command line
std::string folder, dfolder, stamp_file = "stamps.dat", stamp;
CLI::App app{"Find pseudo-GT sphere parameters from point cloud data"};
app.add_option("--folder", folder, "folder of input point clouds")->required();
app.add_option("--stamps", stamp_file, "file containing stamps of all point clouds");
app.add_option("--dfolder", dfolder, "folder containing detection results")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::ifstream infile(folder + stamp_file);
while (!infile.eof()) {
infile >> stamp;
std::cout << stamp << std::endl;
std::ifstream infile_det(dfolder + stamp + "/" + stamp + "_o100111.dat");
PointCloudData pc(folder + stamp + ".ply");
std::vector<Sphere<double>*> spheres_vec;
float votes;
Eigen::Vector3d c;
double r;
size_t counter = 0;
infile_det >> votes;
bool conv;
while (!infile_det.eof()) {
infile_det >> c[0] >> c[1] >> c[2] >> r >> votes;
Sphere<double>* S = new Sphere<double>(c, r);
SphereOptimizer<PointCloudData> so(S);
T.tic();
conv = so.optimize(pc);
T.toc();
if (conv)
spheres_vec.push_back(S);
else
delete S;
if (votes < 500)
break;
}
std::ofstream outfile(folder + stamp + ".info");
outfile << "# stamp\n";
outfile << "# num_spheres\n";
outfile << "# cx cy cz r\n";
outfile << stamp << "\n";
outfile << spheres_vec.size() << "\n";
std::cout << spheres_vec.size() << std::endl;
for (auto S : spheres_vec) {
outfile << (*S) << "\n";
delete S;
}
outfile.close();
}
infile.close();
return 0;
}
| 3,188
|
C++
|
.cpp
| 82
| 31.95122
| 101
| 0.626305
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,794
|
main_voting_sample_lib.cpp
|
c-sommer_primitect/cpp/detect_objects/main_voting_sample_lib.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "sampling/PcSampler.hpp"
#include "detector/detectors.h"
#include "detection_metrics.h"
int detect(int argc, char** argv) {
Timer T;
std::string folder, infile, results, otype;
int det_settings = 64;
size_t num_points = 4096;
bool is_scene = true, is_object = false;
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
app.add_option("--results", results, "folder where results shall be written")->required();
app.add_option("--type", otype, "type of object to be detected")->required();
app.add_option("--settings", det_settings, "int specifying DetectorSettings");
app.add_option("--np", num_points, "number of input points to detection stage");
app.add_flag("--o", is_object, "flag for object parts detection");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
if (is_object) {
is_scene = false;
}
std::vector<int> options_vec;
if (det_settings < 64) {
options_vec.push_back(det_settings);
}
else {
options_vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53};
}
enum class Object {
ALL,
PLANE,
SPHERE,
CYLINDER,
CONE,
PLANE_SPHERE,
PLANE_CYL,
PLANE_CONE
};
Object O;
if (otype == "plane") {
O = Object::PLANE;
}
else if (otype == "sphere") {
O = Object::SPHERE;
}
else if (otype == "cylinder") {
O = Object::CYLINDER;
}
else if (otype == "cone") {
O = Object::CONE;
}
else if (otype == "plane-sphere") {
O = Object::PLANE_SPHERE;
}
else if (otype == "plane-cyl") {
O = Object::PLANE_CYL;
}
else if (otype == "plane-cone") {
O = Object::PLANE_CONE;
}
else if (otype == "all") {
O = Object::ALL;
}
else {
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
std::cout << "Number of points: " << pc.num_points() << std::endl;
std::cout << "Diameter of scene: " << pc.diameter() << std::endl;
T.tic();
PcSampler<PointCloudData, float> pcs;
std::vector<size_t> idx = pcs.sample_random(pc, num_points);
pc.sample(idx);
T.toc("Downsample point cloud");
std::cout << "Number of points: " << pc.num_points() << std::endl;
std::cout << "Diameter of scene: " << pc.diameter() << std::endl;
PpfDetector<PointCloudData, float, float>* detector;
for (const int& o : options_vec) {
std::bitset<6> options(o);
DetectorSettings settings(options);
std::cout << std::endl << ".........." << std::endl;
settings.print();
std::cout << std::endl;
switch (O) {
case Object::PLANE :
detector = new PlaneDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::SPHERE :
detector = new SphereDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::CYLINDER :
detector = new CylinderDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::CONE :
detector = new ConeDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_SPHERE :
detector = new PlaneSphereDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_CYL :
detector = new PlaneCylinderDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::PLANE_CONE :
detector = new PlaneConeDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
case Object::ALL :
detector = new PrimitiveDetector<PointCloudData, float, float>(pc.diameter(), is_scene, settings);
break;
default:
std::cerr << "Your specified object type is not supported (yet)." << std::endl;
return 1;
}
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
detector->print_info();
// detector->print_candidates();
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
detector->print_info();
detector->print_candidates(1e3);
detector->write_results(results, infile, 12, .35*num_points);
std::cout << "# inliers, coverage, 80th percentiles, mean residuals and RMS values for candidate objects:" << std::endl;
std::vector<MyObject<float>*> candidates = detector->candidate_vector(12, .35*num_points);
for (auto& obj : candidates) {
std::cout << metric_inliers<PointCloudData, float>(pc, obj) << "\t"
<< metric_coverage<PointCloudData, float>(pc, obj)*100 << "\%\t"
<< metric_p80<PointCloudData, float>(pc, obj) << "\t"
<< metric_mean<PointCloudData, float>(pc, obj) << "\t"
<< metric_rms<PointCloudData, float>(pc, obj) << std::endl;
}
}
delete detector;
return 0;
}
| 6,934
|
C++
|
.cpp
| 169
| 33.360947
| 173
| 0.604927
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,795
|
main_refine_cylinders.cpp
|
c-sommer_primitect/cpp/detect_objects/main_refine_cylinders.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "shapefit/CylinderOptimizer.h"
int main(int argc, char** argv) {
Timer T;
// parse setttings from command line
std::string folder, dfolder, stamp_file = "stamps.dat", stamp;
CLI::App app{"Find pseudo-GT cylinder parameters from point cloud data"};
app.add_option("--folder", folder, "folder of input point clouds")->required();
app.add_option("--stamps", stamp_file, "file containing stamps of all point clouds");
app.add_option("--dfolder", dfolder, "folder containing detection results")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::ifstream infile(folder + stamp_file);
while (!infile.eof()) {
infile >> stamp;
std::cout << stamp << std::endl;
std::ifstream infile_det(dfolder + stamp + "/" + stamp + "_o100111.dat");
PointCloudData pc(folder + stamp + ".ply");
std::vector<Cylinder<double>*> cylinders_vec;
float votes;
Eigen::Vector3d c, a;
double r;
size_t counter = 0;
infile_det >> votes;
bool conv;
while (!infile_det.eof()) {
infile_det >> c[0] >> c[1] >> c[2] >> a[0] >> a[1] >> a[2] >> r >> votes;
Cylinder<double>* C = new Cylinder<double>(c, a, r);
CylinderOptimizer<PointCloudData> co(C);
T.tic();
conv = co.optimize(pc);
T.toc();
if (conv)
cylinders_vec.push_back(C);
else
delete C;
if (votes < 100)
break;
}
std::ofstream outfile(folder + stamp + ".info");
outfile << "# stamp\n";
outfile << "# num_cylinders\n";
outfile << "# cx cy cz ax ay az r\n";
outfile << stamp << "\n";
outfile << cylinders_vec.size() << "\n";
std::cout << cylinders_vec.size() << std::endl;
for (auto C : cylinders_vec) {
outfile << (*C) << "\n";
delete C;
}
outfile.close();
}
infile.close();
return 0;
}
| 3,251
|
C++
|
.cpp
| 82
| 32.719512
| 101
| 0.625839
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,796
|
main_refine_planes.cpp
|
c-sommer_primitect/cpp/detect_objects/main_refine_planes.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "shapefit/PlaneOptimizer.h"
int main(int argc, char** argv) {
Timer T;
// parse setttings from command line
std::string folder, dfolder, stamp_file = "stamps.dat", stamp;
CLI::App app{"Find pseudo-GT Plane parameters from point cloud data"};
app.add_option("--folder", folder, "folder of input point clouds")->required();
app.add_option("--stamps", stamp_file, "file containing stamps of all point clouds");
app.add_option("--dfolder", dfolder, "folder containing detection results")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
std::ifstream infile(folder + stamp_file);
while (!infile.eof()) {
infile >> stamp;
std::cout << stamp << std::endl;
std::ifstream infile_det(dfolder + stamp + "/" + stamp + "_o100111.dat");
PointCloudData pc(folder + stamp + ".ply");
std::vector<Plane<double>*> Planes_vec;
float votes;
Eigen::Vector3d n;
double d;
size_t counter = 0;
infile_det >> votes;
bool conv;
while (!infile_det.eof()) {
infile_det >> n[0] >> n[1] >> n[2] >> d >> votes;
Plane<double>* P = new Plane<double>(n, d);
PlaneOptimizer<PointCloudData> po(P);
T.tic();
conv = po.optimize(pc);
T.toc();
if (conv)
Planes_vec.push_back(P);
else
delete P;
if (votes < 100)
break;
}
std::ofstream outfile(folder + stamp + ".info");
outfile << "# stamp\n";
outfile << "# num_planes\n";
outfile << "# nx ny nz d\n";
outfile << stamp << "\n";
outfile << Planes_vec.size() << "\n";
std::cout << Planes_vec.size() << std::endl;
for (auto P : Planes_vec) {
outfile << (*P) << "\n";
delete P;
}
outfile.close();
}
infile.close();
return 0;
}
| 3,176
|
C++
|
.cpp
| 82
| 31.804878
| 101
| 0.624836
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,797
|
main_cylinder_dr.cpp
|
c-sommer_primitect/cpp/detect_objects/main_cylinder_dr.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "detector/CylinderDetector.h"
#include "shapefit/CylinderOptimizer.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, infile;
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
DetectorSettings settings(std::bitset<6>(39));
CylinderDetector<PointCloudData, float, float>* detector = new CylinderDetector<PointCloudData, float, float>(settings);
CylinderOptimizer<PointCloudData>* optimizer = nullptr;
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
for (auto el : detector->candidates()) {
if (el.first < 1e3) break;
Cylinder<double> C = el.second->cast<double>();
MyObject<double>* obj = static_cast<MyObject<double>*>(&C);
std::cout << std::endl << ".......... # votes: " << el.first << std::endl;
std::cout << "Before refinement:" << std::endl;
std::cout << C << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
optimizer = new CylinderOptimizer<PointCloudData>(&C);
T.tic();
bool conv = optimizer->optimize(pc);
T.toc("Parameter refinement");
if (conv) {
obj = static_cast<MyObject<double>*>(&C);
std::cout << "After refinement:" << std::endl;
std::cout << C << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
}
else {
std::cout << "No convergence." << std::endl;
}
}
delete detector;
if (optimizer) delete optimizer;
return 0;
}
| 3,240
|
C++
|
.cpp
| 78
| 35.512821
| 124
| 0.67557
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,798
|
main_plane_dr.cpp
|
c-sommer_primitect/cpp/detect_objects/main_plane_dr.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "detector/PlaneDetector.h"
#include "shapefit/PlaneOptimizer.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, infile;
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
DetectorSettings settings(std::bitset<6>(39));
PlaneDetector<PointCloudData, float, float>* detector = new PlaneDetector<PointCloudData, float, float>(settings);
PlaneOptimizer<PointCloudData>* optimizer = nullptr;
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
for (auto el : detector->candidates()) {
Plane<double> P = el.second->cast<double>();
MyObject<double>* obj = static_cast<MyObject<double>*>(&P);
std::cout << std::endl << ".......... # votes: " << el.first << std::endl;
std::cout << "Before refinement:" << std::endl;
std::cout << P << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
optimizer = new PlaneOptimizer<PointCloudData>(&P);
T.tic();
bool conv = optimizer->optimize(pc);
T.toc("Parameter refinement");
if (conv) {
obj = static_cast<MyObject<double>*>(&P);
std::cout << "After refinement:" << std::endl;
std::cout << P << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
}
else {
std::cout << "No convergence." << std::endl;
}
}
delete detector;
if (optimizer) delete optimizer;
return 0;
}
| 3,183
|
C++
|
.cpp
| 77
| 35.363636
| 118
| 0.67529
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,799
|
main_cone_dr.cpp
|
c-sommer_primitect/cpp/detect_objects/main_cone_dr.cpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include <CLI/CLI.hpp>
#include "Timer.h"
#include "pcd/PointCloudData.h"
#include "detector/ConeDetector.h"
#include "shapefit/ConeOptimizer.h"
#include "detection_metrics.h"
int main(int argc, char** argv) {
Timer T;
std::string folder, infile, infile2 = "";
CLI::App app{"Detect objects in .ply point cloud"};
app.add_option("--folder", folder, "folder of input and output point cloud")->required();
app.add_option("--in", infile, "input point cloud, in .ply format")->required();
app.add_option("--fine", infile2, "input point cloud high resolution, in .ply format");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
T.tic();
PointCloudData pc(folder + infile);
T.toc("Load ply file");
DetectorSettings settings(std::bitset<6>(39));
ConeDetector<PointCloudData, float, float>* detector = new ConeDetector<PointCloudData, float, float>(settings);
ConeOptimizer<PointCloudData>* optimizer = nullptr;
T.tic();
detector->cast_votes(pc);
T.toc("Voting");
T.tic();
detector->cluster_candidates();
detector->cluster_candidates();
T.toc("Two rounds of clustering");
if (infile2 != "") {
pc = PointCloudData(folder + infile2);
}
for (auto el : detector->candidates()) {
Cone<double> C = el.second->cast<double>();
MyObject<double>* obj = static_cast<MyObject<double>*>(&C);
std::cout << std::endl << ".......... # votes: " << el.first << std::endl;
std::cout << "Before refinement:" << std::endl;
std::cout << C << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
optimizer = new ConeOptimizer<PointCloudData>(&C);
T.tic();
bool conv = optimizer->optimize(pc);
T.toc("Parameter refinement");
if (conv) {
obj = static_cast<MyObject<double>*>(&C);
std::cout << "After refinement:" << std::endl;
std::cout << C << std::endl;
print_metrics<PointCloudData, double>(pc, obj);
}
else {
std::cout << "No convergence." << std::endl;
}
}
delete detector;
if (optimizer) delete optimizer;
return 0;
}
| 3,374
|
C++
|
.cpp
| 81
| 35.506173
| 116
| 0.670326
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,801
|
PcSampler.hpp
|
c-sommer_primitect/cpp/include/sampling/PcSampler.hpp
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PC_SAMPLER_H_
#define PC_SAMPLER_H_
#include <iostream>
#include <numeric>
#include <algorithm>
#include <random>
#include <Eigen/Dense>
// #include "Grid.h"
template <class Pcd, typename T>
class PcSampler {
using Vec3 = Eigen::Matrix<T, 3, 1>;
T stepsize_ = 1.; // sample every point
T sampling_ratio_ = 0.01; // 1% of total diameter
T grid_length_ = 0.01;
std::vector<size_t> sample_uniform(Pcd& pc);
std::vector<size_t> sample_grid(Pcd& pc);
void bounding_box(const Pcd& pc, Vec3& min_range, Vec3& max_range);
std::vector<size_t> sort_indices(const Pcd& pc);
public:
std::vector<size_t> sample_uniform(Pcd& pc, size_t num_sampled);
std::vector<size_t> sample_uniform(Pcd& pc, float ratio) {
set_stepsize(static_cast<T>(ratio));
return sample_uniform(pc);
}
std::vector<size_t> sample_uniform(Pcd& pc, double ratio) {
set_stepsize(static_cast<T>(ratio));
return sample_uniform(pc);
}
std::vector<size_t> sample_random(Pcd& pc, size_t num_points);
std::vector<size_t> sample_random(Pcd& pc, float ratio) {
size_t num_points = ratio * pc.num_points();
return sample_random(pc, num_points);
}
std::vector<size_t> sample_random(Pcd& pc, double ratio) {
size_t num_points = ratio * pc.num_points();
return sample_random(pc, num_points);
}
std::vector<size_t> sample_grid(Pcd& pc, T grid_length) {
grid_length_ = grid_length;
return sample_grid(pc);
}
std::vector<size_t> cutoff_z(Pcd& pc, size_t num_points);
void set_stepsize(T ratio) {
stepsize_ = T(1.) / ratio;
}
};
template <class Pcd, typename T>
std::vector<size_t> PcSampler<Pcd, T>::sample_uniform(Pcd& pc) {
T num_points_f = static_cast<T>(pc.num_points());
stepsize_ = std::max(T(1.), std::min(num_points_f, stepsize_));
std::vector<size_t> indices;
for (T idx = 0; idx < pc.num_points(); idx += stepsize_) {
indices.push_back(static_cast<size_t>(idx));
}
stepsize_ = 1.;
return indices;
}
template <class Pcd, typename T>
std::vector<size_t> PcSampler<Pcd, T>::sample_uniform(Pcd& pc, size_t num_sampled) {
T num_points_f = static_cast<T>(pc.num_points());
stepsize_ = num_points_f / num_sampled;
return sample_uniform(pc);
}
template <class Pcd, typename T>
std::vector<size_t> PcSampler<Pcd, T>::sample_random(Pcd& pc, size_t num_points) {
std::vector<size_t> indices(pc.num_points());
std::iota(indices.begin(), indices.end(), 0);
if (pc.num_points() > num_points) {
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(indices.begin(), indices.end(), g);
indices.resize(num_points);
}
return indices;
}
// For license reasons, we can unfortunately not provide the PcSampler<Pcd, T>::sample_grid(Pcd& pc) method in this repository.
template <class Pcd, typename T>
std::vector<size_t> PcSampler<Pcd, T>::sort_indices(const Pcd& pc) {
// initialize original index locations
std::vector<size_t> indices(pc.num_points());
std::iota(indices.begin(), indices.end(), 0);
// sort indices based on comparing z-values in point cloud pc
std::sort(indices.begin(), indices.end(), [&pc](size_t i1, size_t i2) {return pc.point(i1, 2) < pc.point(i2, 2);});
return indices;
}
template <class Pcd, typename T>
std::vector<size_t> PcSampler<Pcd, T>::cutoff_z(Pcd& pc, size_t num_points) {
size_t N = pc.num_points();
std::vector<size_t> indices(N);
if (N <= num_points) {
std::iota(indices.begin(), indices.end(), 0);
}
else {
indices = sort_indices(pc);
indices.resize(num_points);
}
return indices;
}
#endif // PC_SAMPLER_H_
| 4,826
|
C++
|
.h
| 118
| 35.847458
| 127
| 0.676246
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,802
|
Plane.h
|
c-sommer_primitect/cpp/include/objects/Plane.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PLANE_H_
#define PLANE_H_
#include <iostream>
#include <Eigen/Dense>
#include "MyObject.h"
template <typename T> class Plane;
template <typename T> std::ostream& operator<<(std::ostream& os, const Plane<T>& P);
/*
* class Plane
*/
template <typename T>
class Plane : public MyObject<T> {
using Vec3 = Eigen::Matrix<T, 3, 1>;
union {
struct {
Vec3 n_; // plane normal (3D vector with unit norm)
T d_; // distance from plane to origin (scalar)
};
T data_[4];
};
static int sgn(T x) {
return (0. < x) - (x < 0.);
}
public:
Plane(Vec3 n, T d, Vec3 p = Vec3(0., 0., 0.)) : // TODO: replace default rep_
MyObject<T>(p),
n_(n.normalized()),
d_(d)
{}
Plane(const Plane& other) : // TODO: replace default rep_
MyObject<T>(other.rep_),
n_(other.n_),
d_(other.d_)
{}
T sdf(Vec3 p) const {
return n_.dot(p) + d_;
}
Vec3 normal(Vec3 p) const {
return -n_;
}
Vec3 project(Vec3 p) const {
return p - sdf(p) * n_;
}
virtual Vec3 normal_rep() const {
return -n_;
}
T integrate(T w_this, Plane* other, T w_other) {
// TODO: make a better plane averaging by points
T w_new = w_this + w_other;
T w_new_inv = 1. / w_new;
int sign = sgn(n_.dot(other->n_));
n_ = (w_this * n_ + sign * w_other * other->n_).normalized();
d_ = (w_this * d_ + sign * w_other * other->d_) * w_new_inv;
this->rep_ = project(this->rep_);
return w_new;
}
T dist(Plane<T>* other) {
return std::abs(d_ - other->d_);
}
T angle(Plane<T>* other) {
return n_.dot(other->n_);
}
T* data() {
return data_;
}
template <typename U>
Plane<U> cast() {
return Plane<U>(n_.template cast<U>(), U(d_), this->rep_.template cast<U>());
}
friend std::ostream& operator<< <>(std::ostream& os, const Plane<T>& P);
};
/**
* ostream definition
*/
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const Plane<T>& P) {
// display: plane normal (3D), plane distance to origin (1D)
os << P.n_.transpose() << "\t" << P.d_;
return os;
}
#endif // PLANE_H_
| 3,265
|
C++
|
.h
| 100
| 27.72
| 101
| 0.620536
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,803
|
Sphere.h
|
c-sommer_primitect/cpp/include/objects/Sphere.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef SPHERE_H_
#define SPHERE_H_
#include <iostream>
#include <Eigen/Dense>
#include "MyObject.h"
template <typename T> class Sphere;
template <typename T> std::ostream& operator<<(std::ostream& os, const Sphere<T>& S);
/*
* class Sphere
*/
template <typename T>
class Sphere : public MyObject<T> {
using Vec3 = Eigen::Matrix<T, 3, 1>;
union {
struct {
Vec3 c_; // sphere center (3D coordinates)
T r_; // sphere radius (scalar)
};
T data_[4];
};
public:
Sphere(Vec3 c, T r, Vec3 p = Vec3(0., 0., 0.)) : // TODO: replace default rep_
MyObject<T>(p),
c_(c),
r_(r)
{}
Sphere(const Sphere &other) : MyObject<T>(other.rep_),
c_(other.c_),
r_(other.r_)
{}
T sdf(Vec3 p) const {
const Vec3 d = p - c_;
return r_ - d.norm();
}
Vec3 normal(Vec3 p) const {
return (p - c_).normalized();
}
Vec3 project(Vec3 p) const {
const Vec3 d = p - c_;
return p + (r_ / d.norm() - 1.) * d;
}
virtual Vec3 normal_rep() const {
return (this->rep_ - c_) / r_;
}
T integrate(T w_this, Sphere* other, T w_other) {
T w_new = w_this + w_other;
T w_new_inv = 1. / w_new;
c_ = (w_this * c_ + w_other * other->c_) * w_new_inv;
r_ = (w_this * r_ + w_other * other->r_) * w_new_inv;
this->rep_ = project(this->rep_);
return w_new;
}
T dist(Sphere<T>* other) {
return (c_ - other->c_).norm();
}
T r_dist(Sphere<T>* other) {
return r_ - other->r_;
}
T* data() {
return data_;
}
template <typename U>
Sphere<U> cast() {
return Sphere<U>(c_.template cast<U>(), U(r_), this->rep_.template cast<U>());
}
friend std::ostream& operator<< <>(std::ostream& os, const Sphere<T>& S);
};
/**
* ostream definition
*/
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const Sphere<T>& S) {
// display: sphere center (3D), sphere radius (1D)
os << S.c_.transpose() << "\t" << S.r_;
return os;
}
#endif // SPHERE_H_
| 3,120
|
C++
|
.h
| 96
| 27.666667
| 101
| 0.618825
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,804
|
MyObject.h
|
c-sommer_primitect/cpp/include/objects/MyObject.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef MY_OBJECT_H_
#define MY_OBJECT_H_
#include <iostream>
#include <Eigen/Dense>
/*
* class Sphere
*/
template <typename T>
class MyObject {
using Vec3 = Eigen::Matrix<T, 3, 1>;
protected:
Vec3 rep_;
public:
MyObject(Vec3 rep) :
rep_(rep)
{}
virtual T sdf(Vec3 p) const = 0;
virtual Vec3 normal(Vec3 p) const = 0;
virtual Vec3 project(Vec3 p) const = 0;
virtual Vec3 normal_rep() const = 0;
virtual T* data() = 0;
Vec3 rep() {
return rep_;
}
virtual bool are_similar(MyObject<T>* other, T threshold, T cos_max_angle = std::cos(30. * M_PI / 180.)) {
bool pt_sim = std::abs(sdf(other->rep_)) < threshold && std::abs(other->sdf(this->rep_)) < threshold;
bool n_sim = normal(other->rep_).dot(other->normal_rep()) > cos_max_angle && other->normal(this->rep_).dot(normal_rep()) > cos_max_angle;
return pt_sim && n_sim;
}
};
#endif // MY_OBJECT_H_
| 1,951
|
C++
|
.h
| 50
| 35.14
| 145
| 0.712048
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,805
|
Cone.h
|
c-sommer_primitect/cpp/include/objects/Cone.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CONE_H_
#define CONE_H_
#include <iostream>
#include <Eigen/Dense>
#include "MyObject.h"
template <typename T> class Cone;
template <typename T> std::ostream& operator<<(std::ostream& os, const Cone<T>& C);
/*
* class Cone
*/
template <typename T>
class Cone : public MyObject<T> {
using Vec3 = Eigen::Matrix<T, 3, 1>;
union {
struct {
Vec3 c_; // cone apex (3D coordinates)
Vec3 a_; // cone axis (3D vector with unit norm)
T sin_theta_;
T cos_theta_;
T theta_; // cone opening angle (scalar, in radians)
};
T data_[9];
};
T angle_point_axis(Vec3 a) {
T sin_theta = a.dot(a_ - cos_theta_ * (this->rep_ - c_).normalized());
return std::asin(sin_theta);
}
T shift_axis(Vec3 a, Vec3 c) {
Vec3 d = this->rep_ - c;
T h = d.dot(a);
T r = std::sqrt(d.squaredNorm() - h * h);
return r * cos_theta_ / sin_theta_ - h;
}
public:
Cone(Vec3 c, Vec3 a, T sin_theta, Vec3 p = Vec3(0., 0., 0.)) : // TODO: replace default rep_
MyObject<T>(p),
c_(c),
a_(a.normalized()),
sin_theta_(sin_theta),
cos_theta_(std::sqrt(1. - sin_theta * sin_theta)),
theta_(std::asin(sin_theta_))
{}
Cone(const Cone &other) : MyObject<T>(other.rep_),
c_(other.c_),
a_(other.a_),
sin_theta_(other.sin_theta_),
cos_theta_(other.cos_theta_),
theta_(other.theta_)
{}
T sdf(Vec3 p) const {
const Vec3 d = (p - c_);
const T h = d.dot(a_);
const T r = std::sqrt(d.squaredNorm() - h * h);
if (h * cos_theta_ + r * sin_theta_ < 0) // point above cone apex
return -d.norm();
return h * sin_theta_ - r * cos_theta_;
}
Vec3 normal(Vec3 p) const {
const Vec3 d = (p - c_);
const T h = d.dot(a_);
const T r = std::sqrt(d.squaredNorm() - h * h);
if (h * cos_theta_ + r * sin_theta_ < 0) // point above cone apex
return d.normalized();
return -sin_theta_ * a_ + cos_theta_ * (d - h * a_).normalized();
}
Vec3 project(Vec3 p) const { // TODO : possibly improve
const Vec3 d = (p - c_);
const T h = d.dot(a_);
const T r = std::sqrt(d.squaredNorm() - h * h);
if (h * cos_theta_ + r * sin_theta_ < 0) // point above cone apex
return c_;
return p + sdf(p) * normal(p);
}
virtual Vec3 normal_rep() const {
const Vec3 d = (this->rep_ - c_);
return (-a_ + cos_theta_ * d.normalized()) / sin_theta_;
}
T integrate(T w_this, Cone* other, T w_other) {
T w_new = w_this + w_other;
T w_new_inv = 1. / w_new;
c_ = (w_this * c_ + w_other * other->c_) * w_new_inv;
a_ = (w_this * a_ + w_other * other->a_).normalized();
theta_ = (w_this * theta_ + w_other * other->theta_) * w_new_inv;
sin_theta_ = std::sin(theta_);
cos_theta_ = std::cos(theta_);
this->rep_ = project(this->rep_);
return w_new;
}
T dist(Cone<T>* other) {
return (c_ - other->c_).norm();
}
T angle(Cone<T>* other) {
return a_.dot(other->a_);
}
T angle_dist(Cone<T>* other) {
return theta_ - other->theta_;
}
T* data() {
return data_;
}
template <typename U>
Cone<U> cast() {
return Cone<U>(c_.template cast<U>(), a_.template cast<U>(), U(sin_theta_), this->rep_.template cast<U>());
}
friend std::ostream& operator<< <>(std::ostream& os, const Cone<T>& C);
};
/**
* ostream definition
*/
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const Cone<T>& C) {
// display: cone apex (3D), cone axis (3D), cone opening angle (1D)
os << C.c_.transpose() << "\t" << C.a_.transpose() << "\t" << C.theta_;
return os;
}
#endif // CONE_H_
| 4,890
|
C++
|
.h
| 135
| 30.237037
| 115
| 0.58044
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,806
|
Cylinder.h
|
c-sommer_primitect/cpp/include/objects/Cylinder.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CYLINDER_H_
#define CYLINDER_H_
#include <iostream>
#include <Eigen/Dense>
#include "MyObject.h"
template <typename T> class Cylinder;
template <typename T> std::ostream& operator<<(std::ostream& os, const Cylinder<T>& C);
/*
* class Cylinder
*/
template <typename T>
class Cylinder : public MyObject<T> {
using Vec3 = Eigen::Matrix<T, 3, 1>;
union {
struct {
Vec3 c_; // point on cylinder axis (3D coordinates, not uniquely defined)
Vec3 a_; // cylinder axis (3D vector with unit norm)
T r_; // cylinder radius (scalar)
};
T data_[7];
};
static int sgn(T x) {
return (0. < x) - (x < 0.);
}
public:
Cylinder(Vec3 c, Vec3 a, T r, Vec3 p = Vec3(0., 0., 0.)) : // TODO: replace default rep_
MyObject<T>(p),
c_(c),
a_(a.normalized()),
r_(r)
{
}
Cylinder(const Cylinder& other) : // TODO: replace default rep_
MyObject<T>(other.rep_),
c_(other.c_),
a_(other.a_),
r_(other.r_)
{
}
T sdf(Vec3 p) const {
const Vec3 d = p - c_;
return r_ - std::sqrt(d.squaredNorm() - d.dot(a_) * d.dot(a_));
}
Vec3 normal(Vec3 p) const {
const Vec3 d = p - c_;
return (d - a_.dot(d) * a_).normalized();
}
Vec3 project(Vec3 p) const {
const Vec3 d = p - c_;
const T dTa = d.dot(a_);
const T sqr = d.squaredNorm() - dTa * dTa;
return p + (r_ / std::sqrt(sqr) - 1.) * (d - dTa * a_);
}
virtual Vec3 normal_rep() const {
const Vec3 d = this->rep_ - c_;
return (d - a_.dot(d) * a_) / r_;
}
T integrate(T w_this, Cylinder<T>* other, T w_other) {
T w_new = w_this + w_other;
T w_new_inv = 1. / w_new;
int sign = sgn(a_.dot(other->a_));
a_ = (w_this * a_ + sign * w_other * other->a_).normalized();
c_ = (w_this * c_ + w_other * other->c_) * w_new_inv;
r_ = (w_this * r_ + w_other * other->r_) * w_new_inv;
this->rep_ = project(this->rep_);
return w_new;
}
T dist(Cylinder<T>* other) {
Vec3 dc = c_ - other->c_;
return .5 * (std::sqrt(dc.squaredNorm() - dc.dot(a_) * dc.dot(a_)) + std::sqrt(dc.squaredNorm() - dc.dot(other->a_) * dc.dot(other->a_)));
}
T angle(Cylinder<T>* other) {
return a_.dot(other->a_);
}
T r_dist(Cylinder<T>* other) {
return r_ - other->r_;
}
T* data() {
return data_;
}
template <typename U>
Cylinder<U> cast() {
return Cylinder<U>(c_.template cast<U>(), a_.template cast<U>(), U(r_), this->rep_.template cast<U>());
}
friend std::ostream& operator<< <>(std::ostream& os, const Cylinder<T>& C);
};
/**
* ostream definition
*/
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const Cylinder<T>& C) {
// display: point on cylinder axis (3D), cylinder axis (3D), cylinder radius (1D)
os << C.c_.transpose() << "\t" << C.a_.transpose() << "\t" << C.r_;
return os;
}
#endif // CYLINDER_H_
| 4,072
|
C++
|
.h
| 115
| 30.043478
| 146
| 0.597148
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,807
|
PointCloudData.h
|
c-sommer_primitect/cpp/include/pcd/PointCloudData.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef POINT_CLOUD_DATA_H_
#define POINT_CLOUD_DATA_H_
#include <vector>
#include <iostream>
#include <Eigen/Dense>
class PointCloudData {
std::vector<Eigen::Vector3f> points_;
std::vector<Eigen::Vector3f> normals_;
size_t num_points_;
public:
PointCloudData(std::vector<Eigen::Vector3f>& points, std::vector<Eigen::Vector3f>& normals) :
points_(points),
normals_(normals),
num_points_(points.size())
{
}
PointCloudData(std::string filepath);
float point(size_t idx, size_t dim) const {
return points_[idx][dim];
}
float normal(size_t idx, size_t dim) const {
return normals_[idx][dim];
}
Eigen::Vector3f point(size_t idx) const {
return points_[idx];
}
Eigen::Vector3f normal(size_t idx) const {
return normals_[idx];
}
size_t num_points() const {
return num_points_;
}
void normalize() {
for (auto& n : normals_) {
n.normalize();
}
}
void sample(std::vector<size_t> indices) {
std::vector<Eigen::Vector3f> new_points, new_normals;
for (const auto& idx : indices) {
new_points.push_back(points_[idx]);
new_normals.push_back(normals_[idx]);
}
points_ = new_points;
normals_ = new_normals;
num_points_ = points_.size();
}
void scale(float scale) {
for (auto& p : points_) {
p *= scale;
}
}
float diameter() const {
float min_x = std::numeric_limits<float>::max(), min_y = min_x, min_z = min_y;
float max_x = std::numeric_limits<float>::lowest(), max_y = max_x, max_z = max_y;
for (auto& p : points_) {
if (p[0] < min_x) min_x = p[0];
if (p[0] > max_x) max_x = p[0];
if (p[1] < min_y) min_y = p[1];
if (p[1] > max_y) max_y = p[1];
if (p[2] < min_z) min_z = p[2];
if (p[2] > max_z) max_z = p[2];
}
const float dx = max_x - min_x;
const float dy = max_y - min_y;
const float dz = max_z - min_z;
return std::sqrt(dx * dx + dy * dy + dz * dz);
}
void write(std::string filepath);
};
#endif // POINT_CLOUD_DATA_H_
| 3,229
|
C++
|
.h
| 90
| 29.811111
| 101
| 0.623114
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,808
|
PlaneDetector.h
|
c-sommer_primitect/cpp/include/detector/PlaneDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PLANE_DETECTOR_H_
#define PLANE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "objects/Plane.h"
template <class Pcd, typename T, typename VoteT>
class PlaneDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
VoteT counter = 0;
std::multimap<T, Plane<T>*, std::greater<T>> candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 tmp1, Vec3 tmp2) { // conditions: normals parallel, orthogonal to distance vector
if (cppf[3] < this->cos_thresh_) // if normals are not parallel, quit
return;
if (cppf[0] < this->min_dist_sq_) // distance between points to small to distinguish plane from cylinder/cone
return;
if (std::abs(cppf[1]) > this->dist_bin_ || std::abs(cppf[2]) > this->dist_bin_) // points too far from other plane
return;
// this already includes |angle(n, d) - pi/2| < angle_bin_
// if sin(angle_bin_) * 10 > 1
// which is true if angle_bin_ > 5.74° (so we require angle_bin_ >= 6° to be on the safe side)
DetectorSettings& s = this->settings_;
if (!s.ClosenessWeights) {
if (cppf[3] >= this->cos_thresh_half_)
++counter;
}
else {
T bin_inv = this->angle_bin_inv_;
T d_inv = 1. / std::sqrt(cppf[0]);
T weight = (1. - std::acos(cppf[3]) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[1] * d_inv)) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[2] * d_inv)) * bin_inv);
counter += weight;
}
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
if (counter > this->min_votes_) {
candidates_.emplace(counter, new Plane<T>(nr, -nr.dot(pr), pr));
}
}
public:
PlaneDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings)
{}
PlaneDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene)
{}
virtual ~PlaneDetector() {
for (auto& el : candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Plane<T>>(candidates_);
}
virtual void reset() {
counter = 0;
}
const std::multimap<T, Plane<T>*, std::greater<T>>& candidates() const {
return candidates_;
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
T min_vote_sq = min_vote * min_vote;
for (auto el : candidates_) {
if (el.first > min_vote_sq && sum_votes < max_points) {
candidates.push_back(static_cast<MyObject<T>*>(el.second));
sum_votes += std::sqrt(el.first);
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << candidates_.size() << " candidates." << std::endl;
}
virtual void print_votes() const {
std::cout << "Votes for Plane detector:" << counter << std::endl;
}
virtual void print_parameters(Vec3 pr, Vec3 nr) const {
if (counter > 0)
std::cout << "n = (" << nr.transpose() << "),\t d = " << -nr.dot(pr) << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
for (const auto el : candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
sphere_file.close();
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
cyl_file.close();
std::ofstream cone_file(folder + prefix + "_cones.txt");
cone_file.close();
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
Plane<T>* p = dynamic_cast<Plane<T>*>(obj);
plane_file << instance << "\t" << *p << std::endl;
++instance;
}
plane_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // PLANE_DETECTOR_H_
| 6,722
|
C++
|
.h
| 142
| 38.964789
| 171
| 0.605896
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,809
|
PlaneCylinderDetector.h
|
c-sommer_primitect/cpp/include/detector/PlaneCylinderDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PLANE_CYLINDER_DETECTOR_H_
#define PLANE_CYLINDER_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "CylinderVotingTable.h"
#include "objects/Plane.h"
#include "objects/Cylinder.h"
template <class Pcd, typename T, typename VoteT>
class PlaneCylinderDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T radius(Vec4 cppf) {
T denom = 2. * (cppf[3] - 1);
return (cppf[1] - cppf[2]) / denom;
}
T angle(Vec3 ni) {
Vec3 m = this->nr_.cross(ni);
Eigen::Matrix<T, 2, 1> m_rot = this->rot_ * m; // in this setting, no normalization necessary
return std::atan(m_rot[1] / m_rot[0]);
}
VoteT plane_counter = 0;
CylinderVotingTable<T, VoteT> cvt;
std::multimap<T, Plane<T>*, std::greater<T>> plane_candidates_;
std::multimap<T, Cylinder<T>*, std::greater<T>> cyl_candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 tmp, Vec3 ni) { // conditions: normals not parallel, feature symmetric, vectors form triangle
DetectorSettings& s = this->settings_;
if (cppf[3] >= this->cos_thresh_) { // if normals are approximately parallel, no Cylinder voting
if (cppf[0] < this->min_dist_sq_) // distance between points to small to distinguish plane from cylinder/cone
return;
if (std::abs(cppf[1]) > this->dist_bin_ || std::abs(cppf[2]) > this->dist_bin_) // points too far from other plane
return;
// this already includes |angle(n, d) - pi/2| < angle_bin_
// if sin(angle_bin_) * 10 > 1
// which is true if angle_bin_ > 5.74° (so we require angle_bin_ >= 6° to be on the safe side)
if (!s.ClosenessWeights) {
if (cppf[3] >= this->cos_thresh_half_)
++plane_counter;
}
else {
T bin_inv = this->angle_bin_inv_;
T d_inv = 1. / std::sqrt(cppf[0]);
T weight = (1. - std::acos(cppf[3]) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[1] * d_inv)) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[2] * d_inv)) * bin_inv);
plane_counter += weight;
}
return;
}
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
if (s.ApproximatedConditions) { // ApproximatedConditions => !PpfConditions, !ClosenessWeights
// approximated conditions (non-uniform, non-interpretable)
if (std::abs(cppf[1] + cppf[2]) < this->sin_thresh_) {
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
}
else if (!s.PpfConditions) { // !ApproximatedConditions, !PpfConditions
T S1 = std::sqrt(cppf[0] - cppf[1] * cppf[1]);
T S2 = std::sqrt(cppf[0] - cppf[2] * cppf[2]);
T c1 = S1 * S2 - cppf[1] * cppf[2];
if (c1 > this->cos_thresh2_ * cppf[0]) {
if (!s.ClosenessWeights) {
if (c1 > this->cos_thresh_ * cppf[0])
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
else if (c1 < cppf[0]) { // TODO: possibly move condition further up
T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(c1 / cppf[0]) * bin_inv);
cvt.vote(radius(cppf), angle(ni), weight, s.InterpolatedWeights);
}
}
}
else {
Vec4 ppf = PpfDetector<Pcd, T, VoteT>::compute_ppf(cppf);
T w1 = this->angle_bin_ - .5 * std::abs(M_PI - ppf[1] - ppf[2]);
if (w1 > 0) {
if (!s.ClosenessWeights) { // !ApproximatedConditions, PpfConditions, !ClosenessWeights
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
else { // !ApproximatedConditions, PpfConditions, ClosenessWeights
T bin_inv = this->angle_bin_inv_;
T weight = w1 * bin_inv;
cvt.vote(radius(cppf), angle(ni), weight, s.InterpolatedWeights);
}
}
}
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
using Vec2 = Eigen::Matrix<T, 2, 1>;
std::pair<VoteT, Vec2> el = cvt.get_radius_angle(this->settings_.MeanShift);
VoteT cyl_votes = el.first;
if (cyl_votes > plane_counter) {
T radius = el.second[0];
T angle = el.second[1];
Vec3 c = pr - radius * nr;
Vec3 a = this->rot_.transpose() * Vec2(std::cos(angle), std::sin(angle));
cyl_candidates_.emplace(cyl_votes, new Cylinder<T>(c, a, radius, pr));
}
else if (plane_counter > this->min_votes_) {
plane_candidates_.emplace(plane_counter, new Plane<T>(nr, -nr.dot(pr), pr));
}
}
public:
PlaneCylinderDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Rmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
cvt(CylinderVotingTable<T, VoteT>(Rmax, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
PlaneCylinderDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
cvt(CylinderVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
virtual ~PlaneCylinderDetector() {
for (auto& el : plane_candidates_) {
delete el.second;
}
for (auto& el : cyl_candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Plane<T>>(plane_candidates_);
this->template cluster_candidates_base<Cylinder<T>>(cyl_candidates_);
}
virtual void reset() {
plane_counter = 0;
cvt.reset();
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::multimap<T, MyObject<T>*, std::greater<T>> candidate_map;
for (auto el : plane_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : cyl_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
for (auto el : candidate_map) {
if (el.first > min_vote && sum_votes < max_points) {
candidates.push_back(el.second);
sum_votes += el.first;
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << plane_candidates_.size() << " plane candidates," << std::endl
<< cyl_candidates_.size() << " cylinder candidates." << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
os << "# planes:" << std::endl;
for (const auto el : plane_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# cylinders:" << std::endl;
for (const auto el : cyl_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
sphere_file.close();
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
std::ofstream cone_file(folder + prefix + "_cones.txt");
cone_file.close();
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
if (Plane<T>* p = dynamic_cast<Plane<T>*>(obj)) {
plane_file << instance << "\t" << *p << std::endl;
}
else if (Cylinder<T>* c = dynamic_cast<Cylinder<T>*>(obj)) {
cyl_file << instance << "\t" << *c << std::endl;
}
++instance;
}
plane_file.close();
cyl_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // PLANE_CYLINDER_DETECTOR_H_
| 10,836
|
C++
|
.h
| 221
| 38.751131
| 171
| 0.575033
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,810
|
detectors.h
|
c-sommer_primitect/cpp/include/detector/detectors.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "detector/PlaneDetector.h"
#include "detector/SphereDetector.h"
#include "detector/CylinderDetector.h"
#include "detector/ConeDetector.h"
#include "detector/PlaneSphereDetector.h"
#include "detector/PlaneCylinderDetector.h"
#include "detector/PlaneConeDetector.h"
#include "detector/PrimitiveDetector.h"
| 1,281
|
C++
|
.h
| 27
| 46.222222
| 101
| 0.814103
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,811
|
ConeVotingTable.h
|
c-sommer_primitect/cpp/include/detector/ConeVotingTable.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CONE_VOTING_TABLE_H_
#define CONE_VOTING_TABLE_H_
#include <iostream>
#include <Eigen/Dense>
template <typename T>
Eigen::Matrix<size_t, 1, Eigen::Dynamic> sort_indices(const Eigen::Matrix<T, Eigen::Dynamic, 1>& vec) {
// initialize original index locations
Eigen::Matrix<size_t, 1, Eigen::Dynamic> idx = Eigen::Matrix<size_t, Eigen::Dynamic, 1>::Zero(vec.size());
std::iota(idx.data(), idx.data() + idx.size(), 0);
// sort indices based on comparing values in v
std::partial_sort(idx.data(), idx.data() + 5, idx.data() + idx.size(),
[&vec](size_t i1, size_t i2) { return vec[i1] > vec[i2]; });
return idx;
}
template <typename T, typename VoteT>
class ConeVotingTable {
const T Dmax_;
const T binsize_;
const T binsize_2_;
const T binsize_inv_;
const size_t num_angles_;
size_t num_tot_angles_;
const T anglebin_;
const T anglebin_inv_;
VoteT vote_threshold_ = 10;
Eigen::Matrix<size_t, Eigen::Dynamic, 1> num_phi_;
Eigen::Matrix<T, Eigen::Dynamic, 1> bin_phi_inv_;
Eigen::Matrix<size_t, Eigen::Dynamic, 1> sum_num_phi_;
Eigen::Matrix<VoteT, Eigen::Dynamic, Eigen::Dynamic> acc_; // accumulator array
// TODO: array for neighbors! (8 neighbors, of which find 3 smallest) - possibly transpose??
Eigen::Matrix<size_t, 4, Eigen::Dynamic> neighbors_;
// TODO: array containing actual axes - possibly transpose??
Eigen::Matrix<T, 3, Eigen::Dynamic> axes_;
public:
ConeVotingTable(T Dmax, T binsize, T anglebin) :
Dmax_(Dmax),
binsize_(binsize),
binsize_2_(.5 * binsize_),
binsize_inv_(1. / binsize_),
num_angles_(static_cast<size_t>(M_PI / anglebin + .5)),
anglebin_(M_PI / num_angles_),
anglebin_inv_(1. / anglebin_),
num_phi_(Eigen::Matrix<size_t, Eigen::Dynamic, 1>::Zero(num_angles_, 1)),
bin_phi_inv_(Eigen::Matrix<T, Eigen::Dynamic, 1>::Zero(num_angles_, 1)),
sum_num_phi_(Eigen::Matrix<size_t, Eigen::Dynamic, 1>::Zero(num_angles_, 1))
{
num_tot_angles_ = 0;
// TODO: create index arrays
for (size_t i=0; i<num_angles_; ++i) {
T theta = (.5 + i) * anglebin_;
num_phi_[i] = static_cast<size_t>(std::sin(theta) * num_angles_ + .5);
bin_phi_inv_[i] = num_phi_[i] / M_PI;
sum_num_phi_[i] = num_tot_angles_;
num_tot_angles_ += num_phi_[i];
}
// TODO: create accumulator
acc_ = Eigen::Matrix<VoteT, Eigen::Dynamic, Eigen::Dynamic>::Zero(static_cast<size_t>(Dmax_ * binsize_inv_ + 1.5), num_tot_angles_);
neighbors_ = Eigen::Matrix<size_t, 4, Eigen::Dynamic>::Zero(4, num_tot_angles_);
axes_ = Eigen::Matrix<T, 3, Eigen::Dynamic>::Zero(3, num_tot_angles_);
// fill axes
size_t ij = 0;
for (size_t i=0; i<num_angles_; ++i) {
for (size_t j=0; j<num_phi_[i]; ++j) {
T theta = (.5 + i) * anglebin_;
T phi = (.5 + j) * M_PI / num_phi_[i];
axes_(0, ij) = std::cos(phi) * std::sin(theta);
axes_(1, ij) = std::sin(phi) * std::sin(theta);
axes_(2, ij) = std::cos(theta);
++ij;
}
}
// fill neighbors
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cos_dist = axes_.transpose() * axes_;
cos_dist = cos_dist.cwiseAbs();
for (size_t i=0; i<num_tot_angles_; ++i) {
Eigen::Matrix<size_t, Eigen::Dynamic, 1> idx = sort_indices<T>(cos_dist.col(i));
neighbors_.col(i) = idx.segment<4>(1);
}
}
void vote(T axis_dist, Eigen::Matrix<T, 3, 1> axis, bool InterpolatedWeights) { // distinguish between interpolated and integer votes
T idx_f = axis_dist * binsize_inv_;
T theta = (axis[1] > 0) ? std::acos(axis[2]) : (M_PI - std::acos(axis[2]));
T phi = std::atan(axis[1] / axis[0]);
if (phi < 0)
phi += M_PI;
T idy_f = theta * anglebin_inv_;
if (InterpolatedWeights) {
size_t idx = static_cast<size_t>(idx_f + .5);
T wx_minus = .5 + idx - idx_f;
T wx_plus = .5 + idx_f - idx;
if (idy_f < .5) {
T cos_phi = std::cos(phi);
T sin_phi = std::sqrt(1. - cos_phi * cos_phi);
acc_(idx-1, 0) += wx_minus * .25 * (1 + sin_phi) * (1 + cos_phi);
acc_(idx-1, 1) += wx_minus * .25 * (1 + sin_phi) * (1 - cos_phi);
acc_(idx-1, num_tot_angles_-2) += wx_minus * .25 * (1 - sin_phi) * (1 - cos_phi);
acc_(idx-1, num_tot_angles_-1) += wx_minus * .25 * (1 - sin_phi) * (1 + cos_phi);
acc_(idx, 0) += wx_plus * .25 * (1 + sin_phi) * (1 + cos_phi);
acc_(idx, 1) += wx_plus * .25 * (1 + sin_phi) * (1 - cos_phi);
acc_(idx, num_tot_angles_-2) += wx_plus * .25 * (1 - sin_phi) * (1 - cos_phi);
acc_(idx, num_tot_angles_-1) += wx_plus * .25 * (1 - sin_phi) * (1 + cos_phi);
}
else if (idy_f >= num_angles_ - .5) {
T cos_phi = std::cos(phi);
T sin_phi = std::sqrt(1. - cos_phi * cos_phi);
acc_(idx-1, 0) += wx_minus * .25 * (1 - sin_phi) * (1 - cos_phi);
acc_(idx-1, 1) += wx_minus * .25 * (1 - sin_phi) * (1 + cos_phi);
acc_(idx-1, num_tot_angles_-2) += wx_minus * .25 * (1 + sin_phi) * (1 + cos_phi);
acc_(idx-1, num_tot_angles_-1) += wx_minus * .25 * (1 + sin_phi) * (1 - cos_phi);
acc_(idx, 0) += wx_plus * .25 * (1 - sin_phi) * (1 - cos_phi);
acc_(idx, 1) += wx_plus * .25 * (1 - sin_phi) * (1 + cos_phi);
acc_(idx, num_tot_angles_-2) += wx_plus * .25 * (1 + sin_phi) * (1 + cos_phi);
acc_(idx, num_tot_angles_-1) += wx_plus * .25 * (1 + sin_phi) * (1 - cos_phi);
}
else {
size_t idy = static_cast<size_t>(idy_f + .5);
T idz_f = phi * bin_phi_inv_[idy-1];
size_t idz = static_cast<size_t>(idz_f + .5);
T wyz_tmp = (.5 + idy - idy_f) * (.5 + idz - idz_f);
if (idz_f > .5) {
acc_(idx-1, sum_num_phi_[idy-1] + idz-1) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[idy-1] + idz-1) += wx_plus * wyz_tmp;
}
else {
// TODO: possibly make sum_num_phi_ one dim larger and combine the two summands in the second argument
acc_(idx-1, sum_num_phi_[num_angles_-idy] + num_phi_[num_angles_-idy]-1) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[num_angles_-idy] + num_phi_[num_angles_-idy]-1) += wx_plus * wyz_tmp;
}
wyz_tmp = (.5 + idy - idy_f) * (.5 + idz_f - idz);
if (idz_f < num_phi_[idy] - .5) {
acc_(idx-1, sum_num_phi_[idy-1] + idz) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[idy-1] + idz) += wx_plus * wyz_tmp;
}
else {
acc_(idx-1, sum_num_phi_[num_angles_-idy]) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[num_angles_-idy]) += wx_plus * wyz_tmp;
}
idz_f = phi * bin_phi_inv_[idy];
idz = static_cast<size_t>(idz_f + .5);
wyz_tmp = (.5 + idy_f - idy) * (.5 + idz - idz_f);
if (idz_f > .5) {
acc_(idx-1, sum_num_phi_[idy] + idz-1) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[idy] + idz-1) += wx_plus * wyz_tmp;
}
else {
// TODO: possibly make sum_num_phi_ one dim larger and combine the two summands in the second argument
acc_(idx-1, sum_num_phi_[num_angles_-idy-1] + num_phi_[num_angles_-idy]-1) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[num_angles_-idy-1] + num_phi_[num_angles_-idy]-1) += wx_plus * wyz_tmp;
}
wyz_tmp = (.5 + idy_f - idy) * (.5 + idz_f - idz);
if (idz_f < num_phi_[idy] - .5) {
acc_(idx-1, sum_num_phi_[idy] + idz) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[idy] + idz) += wx_plus * wyz_tmp;
}
else {
acc_(idx-1, sum_num_phi_[num_angles_-idy-1]) += wx_minus * wyz_tmp;
acc_(idx, sum_num_phi_[num_angles_-idy-1]) += wx_plus * wyz_tmp;
}
}
}
else {
size_t idy = static_cast<size_t>(idy_f) % num_angles_;
T idz_f = phi * bin_phi_inv_[idy];
// TODO: add modulus to make safe
++acc_(static_cast<size_t>(idx_f), sum_num_phi_[idy] + static_cast<size_t>(idz_f));
}
}
// No ClosenessWeights implementation needed, since no "equality constraints" given
void reset() {
acc_ *= 0;
}
void set_threshold(VoteT threshold) {
vote_threshold_ = threshold;
}
bool not_valid(T axis_dist) {
return (axis_dist - binsize_2_) < 0 || axis_dist > Dmax_ || !std::isfinite(axis_dist); // TODO: second option only if large-angle cones expected
}
void print_votes() const {
std::cout << acc_ << std::endl;
}
std::pair<VoteT, Eigen::Matrix<T, 4, 1>> get_dist_axis(bool MeanShift = false) const {
using Vec4 = Eigen::Matrix<T, 4, 1>;
int max_idx, max_idy;
VoteT max = acc_.maxCoeff(&max_idx, &max_idy);
if (max < .125 * vote_threshold_) {
return std::make_pair(0, Vec4::Zero());
}
if (MeanShift) {
T msx_enum = 0, msx_denom = max;
if (max_idx > 0) {
msx_enum -= acc_(max_idx-1, max_idy);
msx_denom += acc_(max_idx-1, max_idy);
}
if (max_idx+1 < Dmax_ * binsize_inv_) {
msx_enum += acc_(max_idx+1, max_idy);
msx_denom += acc_(max_idx+1, max_idy);
}
T msx = msx_enum / msx_denom;
Eigen::Matrix<T, 3, 1> axis = max * axes_.col(max_idy);
T msy_denom = max;
for (size_t k=0; k<4; ++k) {
size_t n_idy = neighbors_(k, max_idy);
int sign = (axis.dot(axes_.col(n_idy)) > 0) ? 1 : -1;
T weight = acc_(max_idx, n_idy);
msy_denom += weight;
axis += sign * weight * axes_.col(n_idy);
}
axis.normalize();
VoteT votes = msx_denom + msy_denom - max; // TODO: proper mean shift !!
if (votes < vote_threshold_) {
return std::make_pair(0, Vec4::Zero());
}
return std::make_pair(votes, Vec4((max_idx + msx + .5) * binsize_, axis[0], axis[1], axis[2]));
}
else {
return std::make_pair(max, Vec4((max_idx + .5) * binsize_, axes_(0, max_idy), axes_(1, max_idy), axes_(2, max_idy)));
}
}
};
#endif // CONE_VOTING_TABLE_H_
| 12,180
|
C++
|
.h
| 239
| 39.719665
| 152
| 0.514635
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,812
|
SphereDetector.h
|
c-sommer_primitect/cpp/include/detector/SphereDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef SPHERE_DETECTOR_H_
#define SPHERE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "SphereVotingTable.h"
#include "objects/Sphere.h"
template <class Pcd, typename T, typename VoteT>
class SphereDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T radius(Vec4 cppf) {
T denom = 2. * (cppf[3] - 1);
return (cppf[1] - cppf[2]) / denom;
}
SphereVotingTable<T, VoteT> svt;
std::multimap<T, Sphere<T>*, std::greater<T>> candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 tmp1, Vec3 tmp2) { // conditions: normals not parallel, feature symmetric, vectors form triangle
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
if (cppf[3] >= this->cos_thresh_) // if normals are approximately parallel, no sphere voting
return;
DetectorSettings& s = this->settings_;
if (s.ApproximatedConditions) { // ApproximatedConditions => !PpfConditions, !ClosenessWeights
// approximated conditions (non-uniform, non-interpretable)
if (std::abs(cppf[1] + cppf[2]) < this->sin_thresh_ && std::abs(cppf[3] + (cppf[1]*cppf[1] + cppf[2]*cppf[2])/cppf[0] - 1.) < this->sin_thresh_) {
svt.vote(radius(cppf), s.InterpolatedWeights);
}
}
else if (!s.PpfConditions) { // !ApproximatedConditions, !PpfConditions [=> !ClosenessWeights]
T S1 = std::sqrt(cppf[0] - cppf[1] * cppf[1]);
T S2 = std::sqrt(cppf[0] - cppf[2] * cppf[2]);
T S3 = std::sqrt(1. - cppf[3] * cppf[3]);
T c1 = S1 * S2 - cppf[1] * cppf[2];
if (c1 > this->cos_thresh2_ * cppf[0]) {
T c3 = cppf[1] * cppf[2] * cppf[3] + S1 * S2 * cppf[3] + S1 * cppf[2] * S3 - cppf[1] * S2 * S3;
if (c3 > this->cos_thresh_ * cppf[0]) {
if (!s.ClosenessWeights) {
if (c1 > this->cos_thresh_ * cppf[0] && c3 > this->cos_thresh_half_ * cppf[0])
svt.vote(radius(cppf), s.InterpolatedWeights);
}
else if (c1 < cppf[0] && c3 < cppf[0]) { // TODO: possibly move condition further up
T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(c1 / cppf[0]) * bin_inv);
weight *= (1. - std::acos(c3 / cppf[0]) * bin_inv);
svt.vote(radius(cppf), weight, s.InterpolatedWeights);
}
}
}
}
else {
Vec4 ppf = PpfDetector<Pcd, T, VoteT>::compute_ppf(cppf);
T w1 = this->angle_bin_ - .5 * std::abs(M_PI - ppf[1] - ppf[2]);
if (w1 > 0) {
T w3 = this->angle_bin_ - std::abs(ppf[1] - ppf[2] - ppf[3]);
if (w3 > 0) {
if (!s.ClosenessWeights) { // !ApproximatedConditions, PpfConditions, !ClosenessWeights
svt.vote(radius(cppf), s.InterpolatedWeights);
}
else { // !ApproximatedConditions, PpfConditions, ClosenessWeights
T bin_inv = this->angle_bin_inv_;
T weight = w1 * w3 * bin_inv * bin_inv;
svt.vote(radius(cppf), weight, s.InterpolatedWeights);
}
}
}
}
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
std::pair<VoteT, T> el = svt.get_radius(this->settings_.MeanShift);
VoteT votes = el.first;
if (votes > 0) {
T radius = el.second;
Vec3 c = pr - radius * nr;
candidates_.emplace(votes, new Sphere<T>(c, radius, pr));
}
}
public:
SphereDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Rmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
svt(SphereVotingTable<T, VoteT>(Rmax, this->dist_bin_))
{
svt.set_threshold(this->min_votes_);
}
SphereDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
svt(SphereVotingTable<T, VoteT>(this->max_param_, this->dist_bin_))
{
svt.set_threshold(this->min_votes_);
}
virtual ~SphereDetector() {
for (auto& el : candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Sphere<T>>(candidates_);
}
virtual void reset() {
svt.reset();
}
const std::multimap<T, Sphere<T>*, std::greater<T>>& candidates() const {
return candidates_;
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
T min_vote_sq = min_vote * min_vote;
for (auto el : candidates_) {
if (el.first > min_vote_sq && sum_votes < max_points) {
candidates.push_back(static_cast<MyObject<T>*>(el.second));
sum_votes += std::sqrt(el.first);
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << candidates_.size() << " candidates." << std::endl;
}
virtual void print_votes() const {
std::cout << "Votes for sphere detector:" << std::endl;
svt.print_votes();
}
virtual void print_parameters(Vec3 pr, Vec3 nr) const {
std::pair<VoteT, T> el = svt.get_radius(this->settings_.MeanShift);
if (el.first > 0)
std::cout << "c = (" << (pr - el.second * nr).transpose() << "),\t r = " << el.second << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
for (const auto el : candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
plane_file.close();
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
cyl_file.close();
std::ofstream cone_file(folder + prefix + "_cones.txt");
cone_file.close();
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
Sphere<T>* s = dynamic_cast<Sphere<T>*>(obj);
sphere_file << instance << "\t" << *s << std::endl;
++instance;
}
sphere_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // SPHERE_DETECTOR_H_
| 9,123
|
C++
|
.h
| 186
| 38.956989
| 171
| 0.574473
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,813
|
CylinderDetector.h
|
c-sommer_primitect/cpp/include/detector/CylinderDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CYLINDER_DETECTOR_H_
#define CYLINDER_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "CylinderVotingTable.h"
#include "objects/Cylinder.h"
template <class Pcd, typename T, typename VoteT>
class CylinderDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T radius(Vec4 cppf) {
T denom = 2. * (cppf[3] - 1);
return (cppf[1] - cppf[2]) / denom;
}
T angle(Vec3 ni) {
Vec3 m = this->nr_.cross(ni);
Eigen::Matrix<T, 2, 1> m_rot = this->rot_ * m; // in this setting, no normalization necessary
return std::atan(m_rot[1] / m_rot[0]);
}
CylinderVotingTable<T, VoteT> cvt;
std::multimap<T, Cylinder<T>*, std::greater<T>> candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 tmp, Vec3 ni) { // conditions: normals not parallel, feature symmetric, vectors form triangle
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
if (cppf[3] >= this->cos_thresh_) // if normals are approximately parallel, no Cylinder voting
return;
DetectorSettings& s = this->settings_;
if (s.ApproximatedConditions) { // ApproximatedConditions => !PpfConditions, !ClosenessWeights
// approximated conditions (non-uniform, non-interpretable)
if (std::abs(cppf[1] + cppf[2]) < this->sin_thresh_) {
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
}
else if (!s.PpfConditions) { // !ApproximatedConditions, !PpfConditions
T S1 = std::sqrt(cppf[0] - cppf[1] * cppf[1]);
T S2 = std::sqrt(cppf[0] - cppf[2] * cppf[2]);
T c1 = S1 * S2 - cppf[1] * cppf[2];
if (c1 > this->cos_thresh2_ * cppf[0]) {
if (!s.ClosenessWeights) {
if (c1 > this->cos_thresh_ * cppf[0])
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
else if (c1 < cppf[0]) { // TODO: possibly move condition further up
T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(c1 / cppf[0]) * bin_inv);
cvt.vote(radius(cppf), angle(ni), weight, s.InterpolatedWeights);
}
}
}
else {
Vec4 ppf = PpfDetector<Pcd, T, VoteT>::compute_ppf(cppf);
T w1 = this->angle_bin_ - .5 * std::abs(M_PI - ppf[1] - ppf[2]);
if (w1 > 0) {
if (!s.ClosenessWeights) { // !ApproximatedConditions, PpfConditions, !ClosenessWeights
cvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
else { // !ApproximatedConditions, PpfConditions, ClosenessWeights
T bin_inv = this->angle_bin_inv_;
T weight = w1 * bin_inv;
cvt.vote(radius(cppf), angle(ni), weight, s.InterpolatedWeights);
}
}
}
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
using Vec2 = Eigen::Matrix<T, 2, 1>;
std::pair<VoteT, Vec2> el = cvt.get_radius_angle(this->settings_.MeanShift);
VoteT votes = el.first;
if (votes > 0) {
T radius = el.second[0];
T angle = el.second[1];
Vec3 c = pr - radius * nr;
Vec3 a = this->rot_.transpose() * Vec2(std::cos(angle), std::sin(angle));
candidates_.emplace(votes, new Cylinder<T>(c, a, radius, pr));
}
}
public:
CylinderDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Rmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
cvt(CylinderVotingTable<T, VoteT>(Rmax, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
CylinderDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
cvt(CylinderVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
virtual ~CylinderDetector() {
for (auto& el : candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Cylinder<T>>(candidates_);
}
virtual void reset() {
cvt.reset();
}
const std::multimap<T, Cylinder<T>*, std::greater<T>>& candidates() const {
return candidates_;
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
T min_vote_sq = min_vote * min_vote;
for (auto el : candidates_) {
if (el.first > min_vote_sq && sum_votes < max_points) {
candidates.push_back(static_cast<MyObject<T>*>(el.second));
sum_votes += std::sqrt(el.first);
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << candidates_.size() << " candidates." << std::endl;
}
virtual void print_votes() const {
std::cout << "Votes for cylinder detector:" << std::endl;
cvt.print_votes();
}
virtual void write_candidates(std::ostream& os) const {
for (const auto el : candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
plane_file.close();
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
sphere_file.close();
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
std::ofstream cone_file(folder + prefix + "_cones.txt");
cone_file.close();
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
Cylinder<T>* c = dynamic_cast<Cylinder<T>*>(obj);
cyl_file << instance << "\t" << *c << std::endl;
++instance;
}
cyl_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // CYLINDER_DETECTOR_H_
| 8,674
|
C++
|
.h
| 181
| 38.508287
| 171
| 0.593145
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,814
|
SphereVotingTable.h
|
c-sommer_primitect/cpp/include/detector/SphereVotingTable.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef SPHERE_VOTING_TABLE_H_
#define SPHERE_VOTING_TABLE_H_
#include <iostream>
#include <Eigen/Dense>
template <typename T, typename VoteT>
class SphereVotingTable {
const T Rmax_;
const T binsize_;
const T binsize_2_;
const T binsize_inv_;
VoteT vote_threshold_ = 10;
Eigen::Matrix<VoteT, Eigen::Dynamic, 1> acc_; // accumulator array
bool not_valid(T radius) {
return (radius - binsize_2_) < 0 || radius > Rmax_ || !std::isfinite(radius);
}
public:
SphereVotingTable(T Rmax, T binsize) :
Rmax_(Rmax),
binsize_(binsize),
binsize_2_(.5 * binsize_),
binsize_inv_(1. / binsize_),
acc_(Eigen::Matrix<VoteT, Eigen::Dynamic, 1>::Zero(static_cast<size_t>(Rmax_ * binsize_inv_ + 1.5), 1))
{
}
void vote(T radius, bool InterpolatedWeights) { // distinguish between interpolated and integer votes
if (not_valid(radius))
return;
T idx_f = radius * binsize_inv_;
if (InterpolatedWeights) {
size_t idx = static_cast<size_t>(idx_f + .5);
acc_[idx-1] += (.5 + idx - idx_f);
acc_[idx] += (.5 + idx_f - idx);
}
else {
++acc_[static_cast<size_t>(idx_f)];
}
}
void vote(T radius, T weight, bool InterpolatedWeights) {
if (not_valid(radius))
return;
T idx_f = radius * binsize_inv_;
if (InterpolatedWeights) {
size_t idx = static_cast<size_t>(idx_f + .5);
acc_[idx-1] += weight * (.5 + idx - idx_f);
acc_[idx] += weight * (.5 + idx_f - idx);
}
else {
acc_[static_cast<size_t>(idx_f)] += weight;
}
}
void reset() {
acc_ *= 0;
}
void set_threshold(VoteT threshold) {
vote_threshold_ = threshold;
}
void print_votes() const {
for (size_t idx = 0; idx <= Rmax_ * binsize_inv_ + .5; ++idx) {
std::cout << (idx + .5) * binsize_ << "\t" << acc_[idx] << std::endl;
}
}
std::pair<VoteT, T> get_radius(bool MeanShift = false) const {
int max_idx, tmp;
VoteT max = acc_.maxCoeff(&max_idx, &tmp);
if (max < .5 * vote_threshold_) {
return std::make_pair(0, 0);
}
if (MeanShift) {
T ms_enum = 0, ms_denom = max;
if (max_idx > 0) {
ms_enum -= acc_[max_idx-1];
ms_denom += acc_[max_idx-1];
}
if (max_idx+1 < Rmax_ * binsize_inv_) {
ms_enum += acc_[max_idx+1];
ms_denom += acc_[max_idx+1];
}
T ms = ms_enum / ms_denom;
VoteT votes = ms_denom;//(ms<0) ? (max + acc_[max_idx-1]) : (max + acc_[max_idx+1]);
if (votes < vote_threshold_) {
return std::make_pair(0, 0);
}
return std::make_pair(votes, (max_idx + ms + .5) * binsize_);
}
else {
return std::make_pair(max, (max_idx + .5) * binsize_);
}
}
};
#endif // SPHERE_VOTING_TABLE_H_
| 4,117
|
C++
|
.h
| 109
| 29.889908
| 111
| 0.577293
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,815
|
ConeDetector.h
|
c-sommer_primitect/cpp/include/detector/ConeDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CONE_DETECTOR_H_
#define CONE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "ConeVotingTable.h"
#include "objects/Cone.h"
template <class Pcd, typename T, typename VoteT>
class ConeDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T axis_dist(Vec4 cppf) {
return cppf[2] / (1. - cppf[3]);
}
Vec3 axis(Vec4 cppf, Vec3 pi, Vec3 ni) {
Vec3 a = this->pr_ - pi + (cppf[2] * this->nr_ + cppf[1] * ni) / (cppf[3] - 1.);
return a.normalized();
}
ConeVotingTable<T, VoteT> cvt;
std::multimap<T, Cone<T>*, std::greater<T>> candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 pi, Vec3 ni) { // conditions: normals not parallel, feature symmetric, vectors form triangle
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
if (cppf[3] >= this->cos_thresh_) // if normals are approximately parallel, no cone voting
return;
DetectorSettings& s = this->settings_;
T dist = axis_dist(cppf);
// Vec3 a = axis(cppf, pi, ni);
// T sin_t = std::abs(a.dot(this->nr_));
// dist = (1. - sin_t * sin_t) * dist / sin_t;
if (cvt.not_valid(dist))
return;
// do not impose any anti-degeneracy conditions
cvt.vote(dist, axis(cppf, pi, ni), s.InterpolatedWeights);
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
using Vec2 = Eigen::Matrix<T, 2, 1>;
std::pair<VoteT, Vec4> el = cvt.get_dist_axis(this->settings_.MeanShift);
VoteT votes = el.first;
if (votes > 0) {
T dist = el.second[0];
Vec3 a(el.second[1], el.second[2], el.second[3]);
Vec3 c = pr + dist * (a / a.dot(nr) - nr);
a = (a.dot(pr - c) > 0) ? a : -a;
T sin_theta = -a.dot(nr);
// T sin_theta = a.dot(nr);
// a = sin_theta > 0 ? -a : a;
// sin_theta = std::abs(sin_theta);
// Vec3 c = pr - dist * (a + sin_theta * nr) / (1 - sin_theta * sin_theta);
// discard if opening angle too small (i.e. close to cylinder), or too large (i.e. close to plane)
// but should not actually be necessary since these options are already excluded --> TODO: investigate/debug!
if (sin_theta < this->sin_thresh_ || sin_theta > this->cos_thresh2_)
return;
candidates_.emplace(votes, new Cone<T>(c, a, sin_theta, pr));
}
}
public:
ConeDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Dmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
cvt(ConeVotingTable<T, VoteT>(Dmax, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
ConeDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
cvt(ConeVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
virtual ~ConeDetector() {
for (auto& el : candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Cone<T>>(candidates_);
}
virtual void reset() {
cvt.reset();
}
const std::multimap<T, Cone<T>*, std::greater<T>>& candidates() const {
return candidates_;
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
T min_vote_sq = min_vote * min_vote;
for (auto el : candidates_) {
if (el.first > min_vote_sq && sum_votes < max_points) {
candidates.push_back(static_cast<MyObject<T>*>(el.second));
sum_votes += std::sqrt(el.first);
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << candidates_.size() << " candidates." << std::endl;
}
virtual void print_votes() const {
std::cout << "Votes for Cone detector:" << std::endl;
cvt.print_votes();
}
virtual void write_candidates(std::ostream& os) const {
for (const auto el : candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
plane_file.close();
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
sphere_file.close();
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
cyl_file.close();
std::ofstream cone_file(folder + prefix + "_cones.txt");
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
Cone<T>* c = dynamic_cast<Cone<T>*>(obj);
cone_file << instance << "\t" << *c << std::endl;
++instance;
}
cone_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // CONE_DETECTOR_H_
| 7,573
|
C++
|
.h
| 160
| 39.4625
| 171
| 0.602881
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,816
|
PlaneSphereDetector.h
|
c-sommer_primitect/cpp/include/detector/PlaneSphereDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PLANE_SPHERE_DETECTOR_H_
#define PLANE_SPHERE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "SphereVotingTable.h"
#include "objects/Plane.h"
#include "objects/Sphere.h"
template <class Pcd, typename T, typename VoteT>
class PlaneSphereDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T radius(Vec4 cppf) {
T denom = 2. * (cppf[3] - 1);
return (cppf[1] - cppf[2]) / denom;
}
VoteT plane_counter = 0;
SphereVotingTable<T, VoteT> svt;
std::multimap<T, Plane<T>*, std::greater<T>> plane_candidates_;
std::multimap<T, Sphere<T>*, std::greater<T>> sphere_candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 tmp1, Vec3 tmp2) { // conditions: normals not parallel, feature symmetric, vectors form triangle
DetectorSettings& s = this->settings_;
if (cppf[3] >= this->cos_thresh_) { // if normals are approximately parallel, no sphere voting
if (cppf[0] < this->min_dist_sq_) // distance between points to small to distinguish plane from cylinder/cone
return;
if (std::abs(cppf[1]) > this->dist_bin_ || std::abs(cppf[2]) > this->dist_bin_) // points too far from other plane
return;
// this already includes |angle(n, d) - pi/2| < angle_bin_
// if sin(angle_bin_) * 10 > 1
// which is true if angle_bin_ > 5.74° (so we require angle_bin_ >= 6° to be on the safe side)
if (!s.ClosenessWeights) {
if (cppf[3] >= this->cos_thresh_half_)
++plane_counter;
}
else {
T bin_inv = this->angle_bin_inv_;
T d_inv = 1. / std::sqrt(cppf[0]);
T weight = (1. - std::acos(cppf[3]) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[1] * d_inv)) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[2] * d_inv)) * bin_inv);
plane_counter += weight;
}
return;
}
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
if (s.ApproximatedConditions) { // ApproximatedConditions => !PpfConditions, !ClosenessWeights
// approximated conditions (non-uniform, non-interpretable)
if (std::abs(cppf[1] + cppf[2]) < this->sin_thresh_ && std::abs(cppf[3] + (cppf[1]*cppf[1] + cppf[2]*cppf[2])/cppf[0] - 1.) < this->sin_thresh_) {
svt.vote(radius(cppf), s.InterpolatedWeights);
}
}
else if (!s.PpfConditions) { // !ApproximatedConditions, !PpfConditions [=> !ClosenessWeights]
T S1 = std::sqrt(cppf[0] - cppf[1] * cppf[1]);
T S2 = std::sqrt(cppf[0] - cppf[2] * cppf[2]);
T S3 = std::sqrt(1. - cppf[3] * cppf[3]);
T c1 = S1 * S2 - cppf[1] * cppf[2];
if (c1 > this->cos_thresh2_ * cppf[0]) {
T c3 = cppf[1] * cppf[2] * cppf[3] + S1 * S2 * cppf[3] + S1 * cppf[2] * S3 - cppf[1] * S2 * S3;
if (c3 > this->cos_thresh_ * cppf[0]) {
if (!s.ClosenessWeights) {
if (c1 > this->cos_thresh_ * cppf[0] && c3 > this->cos_thresh_half_ * cppf[0])
svt.vote(radius(cppf), s.InterpolatedWeights);
}
else if (c1 < cppf[0] && c3 < cppf[0]) { // TODO: possibly move condition further up
T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(c1 / cppf[0]) * bin_inv);
weight *= (1. - std::acos(c3 / cppf[0]) * bin_inv);
svt.vote(radius(cppf), weight, s.InterpolatedWeights);
}
}
}
}
else {
Vec4 ppf = PpfDetector<Pcd, T, VoteT>::compute_ppf(cppf);
T w1 = this->angle_bin_ - .5 * std::abs(M_PI - ppf[1] - ppf[2]);
if (w1 > 0) {
T w3 = this->angle_bin_ - std::abs(ppf[1] - ppf[2] - ppf[3]);
if (w3 > 0) {
if (!s.ClosenessWeights) { // !ApproximatedConditions, PpfConditions, !ClosenessWeights
svt.vote(radius(cppf), s.InterpolatedWeights);
}
else { // !ApproximatedConditions, PpfConditions, ClosenessWeights
T bin_inv = this->angle_bin_inv_;
T weight = w1 * w3 * bin_inv * bin_inv;
svt.vote(radius(cppf), weight, s.InterpolatedWeights);
}
}
}
}
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
std::pair<VoteT, T> el = svt.get_radius(this->settings_.MeanShift);
VoteT sphere_votes = el.first;
if (sphere_votes > plane_counter) {
T radius = el.second;
Vec3 c = pr - radius * nr;
sphere_candidates_.emplace(sphere_votes, new Sphere<T>(c, radius, pr));
}
else if (plane_counter > this->min_votes_) {
plane_candidates_.emplace(plane_counter, new Plane<T>(nr, -nr.dot(pr), pr));
}
}
public:
PlaneSphereDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Rmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
svt(SphereVotingTable<T, VoteT>(Rmax, this->dist_bin_))
{
svt.set_threshold(this->min_votes_);
}
PlaneSphereDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
svt(SphereVotingTable<T, VoteT>(this->max_param_, this->dist_bin_))
{
svt.set_threshold(this->min_votes_);
}
virtual ~PlaneSphereDetector() {
for (auto& el : plane_candidates_) {
delete el.second;
}
for (auto& el : sphere_candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Plane<T>>(plane_candidates_);
this->template cluster_candidates_base<Sphere<T>>(sphere_candidates_);
}
virtual void reset() {
plane_counter = 0;
svt.reset();
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::multimap<T, MyObject<T>*, std::greater<T>> candidate_map;
for (auto el : plane_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : sphere_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
for (auto el : candidate_map) {
if (el.first > min_vote && sum_votes < max_points) {
candidates.push_back(el.second);
sum_votes += el.first;
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << plane_candidates_.size() << " plane candidates," << std::endl
<< sphere_candidates_.size() << " sphere candidates." << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
os << "# planes:" << std::endl;
for (const auto el : plane_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# spheres:" << std::endl;
for (const auto el : sphere_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
cyl_file.close();
std::ofstream cone_file(folder + prefix + "_cones.txt");
cone_file.close();
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
if (Plane<T>* p = dynamic_cast<Plane<T>*>(obj)) {
plane_file << instance << "\t" << *p << std::endl;
}
else if (Sphere<T>* s = dynamic_cast<Sphere<T>*>(obj)) {
sphere_file << instance << "\t" << *s << std::endl;
}
++instance;
}
plane_file.close();
sphere_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // PLANE_SPHERE_DETECTOR_H_
| 11,035
|
C++
|
.h
| 221
| 39.058824
| 171
| 0.562535
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,817
|
CylinderVotingTable.h
|
c-sommer_primitect/cpp/include/detector/CylinderVotingTable.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef CYLINDER_VOTING_TABLE_H_
#define CYLINDER_VOTING_TABLE_H_
#include <iostream>
#include <Eigen/Dense>
template <typename T, typename VoteT>
class CylinderVotingTable {
const T Rmax_;
const T binsize_;
const T binsize_2_;
const T binsize_inv_;
const size_t num_angles_;
const T anglebin_;
const T anglebin_inv_;
VoteT vote_threshold_ = 10;
Eigen::Matrix<VoteT, Eigen::Dynamic, Eigen::Dynamic> acc_; // accumulator array
bool not_valid(T radius) {
return (radius - binsize_2_) < 0 || radius > Rmax_ || !std::isfinite(radius);
}
public:
CylinderVotingTable(T Rmax, T binsize, T anglebin) :
Rmax_(Rmax),
binsize_(binsize),
binsize_2_(.5 * binsize_),
binsize_inv_(1. / binsize_),
num_angles_(static_cast<size_t>(M_PI / anglebin + .5)),
anglebin_(M_PI / num_angles_),
anglebin_inv_(1. / anglebin_),
acc_(Eigen::Matrix<VoteT, Eigen::Dynamic, Eigen::Dynamic>::Zero(static_cast<size_t>(Rmax_ * binsize_inv_ + 1.5), num_angles_))
{
}
void vote(T radius, T angle, bool InterpolatedWeights) { // distinguish between interpolated and integer votes
if (not_valid(radius) || !std::isfinite(angle))
return;
T idx_f = radius * binsize_inv_;
T idy_f = angle * anglebin_inv_;
if (idy_f < 0)
idy_f += M_PI * anglebin_inv_; // TODO: replace by num_angles_
if (InterpolatedWeights) {
size_t idx = static_cast<size_t>(idx_f + .5);
size_t idy = static_cast<size_t>(idy_f + .5);
if (idy > 0) {
acc_(idx-1, idy-1) += (.5 + idx - idx_f) * (.5 + idy - idy_f);
acc_(idx, idy-1) += (.5 + idx_f - idx) * (.5 + idy - idy_f);
}
else {
acc_(idx-1, num_angles_-1) += (.5 + idx - idx_f) * (.5 + idy - idy_f);
acc_(idx, num_angles_-1) += (.5 + idx_f - idx) * (.5 + idy - idy_f);
}
if (idy < num_angles_) {
acc_(idx-1, idy) += (.5 + idx - idx_f) * (.5 + idy_f - idy);
acc_(idx, idy) += (.5 + idx_f - idx) * (.5 + idy_f - idy);
}
else {
acc_(idx-1, 0) += (.5 + idx - idx_f) * (.5 + idy_f - idy);
acc_(idx, 0) += (.5 + idx_f - idx) * (.5 + idy_f - idy);
}
}
else {
++acc_(static_cast<size_t>(idx_f), static_cast<size_t>(idy_f) % num_angles_);
}
}
void vote(T radius, T angle, T weight, bool InterpolatedWeights) {
if (not_valid(radius) || !std::isfinite(angle))
return;
T idx_f = radius * binsize_inv_;
T idy_f = angle * anglebin_inv_;
if (idy_f < 0)
idy_f += M_PI * anglebin_inv_; // TODO: replace by num_angles_
if (InterpolatedWeights) {
size_t idx = static_cast<size_t>(idx_f + .5);
size_t idy = static_cast<size_t>(idy_f + .5);
if (idy > 0) {
acc_(idx-1, idy-1) += weight * (.5 + idx - idx_f) * (.5 + idy - idy_f);
acc_(idx, idy-1) += weight * (.5 + idx_f - idx) * (.5 + idy - idy_f);
}
else {
acc_(idx-1, num_angles_-1) += weight * (.5 + idx - idx_f) * (.5 + idy - idy_f);
acc_(idx, num_angles_-1) += weight * (.5 + idx_f - idx) * (.5 + idy - idy_f);
}
if (idy < num_angles_) {
acc_(idx-1, idy) += weight * (.5 + idx - idx_f) * (.5 + idy_f - idy);
acc_(idx, idy) += weight * (.5 + idx_f - idx) * (.5 + idy_f - idy);
}
else {
acc_(idx-1, 0) += weight * (.5 + idx - idx_f) * (.5 + idy_f - idy);
acc_(idx, 0) += weight * (.5 + idx_f - idx) * (.5 + idy_f - idy);
}
}
else {
acc_(static_cast<size_t>(idx_f), static_cast<size_t>(idy_f) % num_angles_) += weight;
}
}
void reset() {
acc_ *= 0;
}
void set_threshold(VoteT threshold) {
vote_threshold_ = threshold;
}
void print_votes() const {
std::cout << acc_ << std::endl;
}
std::pair<VoteT, Eigen::Matrix<T, 2, 1>> get_radius_angle(bool MeanShift = false) const {
using Vec2 = Eigen::Matrix<T, 2, 1>;
int max_idx, max_idy;
VoteT max = acc_.maxCoeff(&max_idx, &max_idy);
if (max < .25 * vote_threshold_) {
return std::make_pair(0, Vec2(0, 0));
}
if (MeanShift) {
T msx_enum = 0, msx_denom = max, msy_enum = 0, msy_denom = max;
if (max_idx > 0) {
msx_enum -= acc_(max_idx-1, max_idy);
msx_denom += acc_(max_idx-1, max_idy);
}
if (max_idx+1 < Rmax_ * binsize_inv_) {
msx_enum += acc_(max_idx+1, max_idy);
msx_denom += acc_(max_idx+1, max_idy);
}
if (max_idy > 0) {
msy_enum -= acc_(max_idx, max_idy-1);
msy_denom += acc_(max_idx, max_idy-1);
} else {
msy_enum -= acc_(max_idx, acc_.cols()-1);
msy_denom -= acc_(max_idx, acc_.cols()-1);
}
if (max_idy+1 < acc_.cols()) {
msy_enum += acc_(max_idx, max_idy+1);
msy_denom += acc_(max_idx, max_idy+1);
} else {
msy_enum += acc_(max_idx, 0);
msy_denom += acc_(max_idx, 0);
}
T msx = msx_enum / msx_denom;
T msy = msy_enum / msy_denom;
VoteT votes = msx_denom + msy_denom - max; // TODO: proper mean shift !! //(ms<0) ? (max + acc_[max_idx-1]) : (max + acc_[max_idx+1]);
if (votes < vote_threshold_) {
return std::make_pair(0, Vec2(0, 0));
}
return std::make_pair(votes, Vec2((max_idx + msx + .5) * binsize_, (max_idy + msy +.5) * anglebin_));
}
else {
return std::make_pair(max, Vec2((max_idx + .5) * binsize_, (max_idy + .5) * anglebin_));
}
}
};
#endif // CYLINDER_VOTING_TABLE_H_
| 7,196
|
C++
|
.h
| 165
| 33.690909
| 146
| 0.513572
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,818
|
PrimitiveDetector.h
|
c-sommer_primitect/cpp/include/detector/PrimitiveDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PRIMITIVE_DETECTOR_H_
#define PRIMITIVE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "CylinderVotingTable.h"
#include "objects/Plane.h"
#include "objects/Cylinder.h"
template <class Pcd, typename T, typename VoteT>
class PrimitiveDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T radius(Vec4 cppf) {
T denom = 2. * (cppf[3] - 1);
return (cppf[1] - cppf[2]) / denom;
}
T angle(Vec3 ni) {
Vec3 m = this->nr_.cross(ni);
Eigen::Matrix<T, 2, 1> m_rot = this->rot_ * m; // in this setting, no normalization necessary
return std::atan(m_rot[1] / m_rot[0]);
}
static T axis_dist(Vec4 cppf) {
return cppf[2] / (1. - cppf[3]);
}
Vec3 axis(Vec4 cppf, Vec3 pi, Vec3 ni) {
Vec3 a = this->pr_ - pi + (cppf[2] * this->nr_ + cppf[1] * ni) / (cppf[3] - 1.);
return a.normalized();
}
VoteT plane_counter = 0;
SphereVotingTable<T, VoteT> svt;
CylinderVotingTable<T, VoteT> cyvt;
ConeVotingTable<T, VoteT> covt;
std::multimap<T, Plane<T>*, std::greater<T>> plane_candidates_;
std::multimap<T, Sphere<T>*, std::greater<T>> sphere_candidates_;
std::multimap<T, Cylinder<T>*, std::greater<T>> cyl_candidates_;
std::multimap<T, Cone<T>*, std::greater<T>> cone_candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 pi, Vec3 ni) {
DetectorSettings& s = this->settings_;
// ---------- PLANE ----------
if (cppf[3] >= this->cos_thresh_) { // if normals are approximately parallel, check rest of plane conditions
if (cppf[0] < this->min_dist_sq_) // distance between points to small to distinguish plane from cylinder/cone
return;
if (std::abs(cppf[1]) > this->dist_bin_ || std::abs(cppf[2]) > this->dist_bin_) // points too far from other plane
return;
// this already includes |angle(n, d) - pi/2| < angle_bin_
// if sin(angle_bin_) * 10 > 1
// which is true if angle_bin_ > 5.74° (so we require angle_bin_ >= 6° to be on the safe side)
if (!s.ClosenessWeights) {
if (cppf[3] >= this->cos_thresh_half_)
++plane_counter;
}
else {
const T bin_inv = this->angle_bin_inv_;
const T d_inv = 1. / std::sqrt(cppf[0]);
T weight = (1. - std::acos(cppf[3]) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[1] * d_inv)) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[2] * d_inv)) * bin_inv);
plane_counter += weight;
}
return;
}
// ---------- NO PLANE ----------
// else doesn't need else-brackets due to return statement
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions": is second point on right side of tangent plane?
return;
// compute "sppf" to check cylinder + sphere conditions
const T S1 = std::sqrt(cppf[0] - cppf[1] * cppf[1]);
const T S2 = std::sqrt(cppf[0] - cppf[2] * cppf[2]);
const T S3 = std::sqrt(1. - cppf[3] * cppf[3]);
const T cos_triangle = cppf[1] * cppf[2] * cppf[3] + S1 * S2 * cppf[3] + S1 * cppf[2] * S3 - cppf[1] * S2 * S3;
const T cos_symmetry = S1 * S2 - cppf[1] * cppf[2];
if (cos_symmetry >= cppf[0] || cos_triangle >= cppf[0]) // data badly conditioned
return;
// ---------- CONE ----------
T dist = axis_dist(cppf);
// Vec3 a = axis(cppf, pi, ni);
// T sin_t = std::abs(a.dot(this->nr_));
// dist = (1. - sin_t * sin_t) * dist / sin_t;
if (!covt.not_valid(dist)) // only compute cone axis if distance is valid
// no ClosenessWeights check necessary, since no equality constraints present for cone
covt.vote(dist, axis(cppf, pi, ni), s.InterpolatedWeights);
// ---------- CYLINDER OR SPHERE ----------
if (cos_symmetry < this->cos_thresh2_ * cppf[0]) // normal projections have to be symmetric w.r.t distance vector
return;
// ---------- CYLINDER ----------
if (!s.ClosenessWeights) {
if (cos_symmetry > this->cos_thresh_ * cppf[0])
cyvt.vote(radius(cppf), angle(ni), s.InterpolatedWeights);
}
else {
const T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(cos_symmetry / cppf[0]) * bin_inv);
cyvt.vote(radius(cppf), angle(ni), weight, s.InterpolatedWeights);
}
// ---------- SPHERE ----------
if (cos_triangle < this->cos_thresh_ * cppf[0]) // condition for sphere: normals and distance vector form triangle
return;
if (!s.ClosenessWeights) {
if (cos_symmetry > this->cos_thresh_ * cppf[0] && cos_triangle > this->cos_thresh_half_ * cppf[0])
svt.vote(radius(cppf), s.InterpolatedWeights);
}
else {
const T bin_inv = this->angle_bin_inv_;
T weight = (1. - .5 * std::acos(cos_symmetry / cppf[0]) * bin_inv);
weight *= (1. - std::acos(cos_triangle / cppf[0]) * bin_inv);
svt.vote(radius(cppf), weight, s.InterpolatedWeights);
}
return;
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
using Vec2 = Eigen::Matrix<T, 2, 1>;
VoteT max_count = this->min_votes_;
int Obj = 0; // no candidate
if (plane_counter > max_count) {
max_count = plane_counter;
Obj = 1; // plane
}
svt.set_threshold(max_count);
std::pair<VoteT, T> el_sphere = svt.get_radius(this->settings_.MeanShift);
if (el_sphere.first > max_count) {
max_count = el_sphere.first;
Obj = 2; // sphere
}
cyvt.set_threshold(max_count);
std::pair<VoteT, Vec2> el_cyl = cyvt.get_radius_angle(this->settings_.MeanShift);
if (el_cyl.first > max_count) {
max_count = el_cyl.first;
Obj = 3; // cylinder
}
covt.set_threshold(max_count);
std::pair<VoteT, Vec4> el_cone = covt.get_dist_axis(this->settings_.MeanShift);
if (el_cone.first > max_count) {
max_count = el_cone.first;
Obj = 4; // cone
}
switch (Obj) {
case 0 :
break;
case 1 : {
plane_candidates_.emplace(max_count, new Plane<T>(nr, -nr.dot(pr), pr));
break;
}
case 2 : {
T radius = el_sphere.second;
Vec3 c = pr - radius * nr;
sphere_candidates_.emplace(max_count, new Sphere<T>(c, radius, pr));
break;
}
case 3 : {
T radius = el_cyl.second[0];
T angle = el_cyl.second[1];
Vec3 c = pr - radius * nr;
Vec3 a = this->rot_.transpose() * Vec2(std::cos(angle), std::sin(angle));
cyl_candidates_.emplace(max_count, new Cylinder<T>(c, a, radius, pr));
break;
}
case 4 : {
T dist = el_cone.second[0];
Vec3 a(el_cone.second[1], el_cone.second[2], el_cone.second[3]);
Vec3 c = pr + dist * (a / a.dot(nr) - nr);
a = (a.dot(pr - c) > 0) ? a : -a;
T sin_theta = -a.dot(nr);
// T sin_theta = a.dot(nr);
// a = sin_theta > 0 ? -a : a;
// sin_theta = std::abs(sin_theta);
// Vec3 c = pr - dist * (a + sin_theta * nr) / (1 - sin_theta * sin_theta);
// discard if opening angle too small (i.e. close to cylinder), or too large (i.e. close to plane)
// but should not actually be necessary since these options are already excluded --> TODO: investigate/debug!
if (sin_theta > this->sin_thresh_ && sin_theta < this->cos_thresh2_)
cone_candidates_.emplace(max_count, new Cone<T>(c, a, sin_theta, pr));
break;
}
}
}
public:
PrimitiveDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Rmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
svt(SphereVotingTable<T, VoteT>(Rmax, this->dist_bin_)),
cyvt(CylinderVotingTable<T, VoteT>(Rmax, this->dist_bin_, this->angle_bin_)),
covt(ConeVotingTable<T, VoteT>(Rmax, this->dist_bin_, this->angle_bin_)) // Dmax = Rmax?!
{
this->settings_.PpfConditions = false; // not yet implemented
this->settings_.ApproximatedConditions = false; // not yet implemented
svt.set_threshold(this->min_votes_);
cyvt.set_threshold(this->min_votes_);
covt.set_threshold(this->min_votes_);
}
PrimitiveDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
svt(SphereVotingTable<T, VoteT>(this->max_param_, this->dist_bin_)),
cyvt(CylinderVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_)),
covt(ConeVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_)) // Dmax = Rmax?!
{
this->settings_.PpfConditions = false; // not yet implemented
this->settings_.ApproximatedConditions = false; // not yet implemented
svt.set_threshold(this->min_votes_);
cyvt.set_threshold(this->min_votes_);
covt.set_threshold(this->min_votes_);
}
virtual ~PrimitiveDetector() {
for (auto& el : plane_candidates_) {
delete el.second;
}
for (auto& el : sphere_candidates_) {
delete el.second;
}
for (auto& el : cyl_candidates_) {
delete el.second;
}
for (auto& el : cone_candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Plane<T>>(plane_candidates_);
this->template cluster_candidates_base<Sphere<T>>(sphere_candidates_);
this->template cluster_candidates_base<Cylinder<T>>(cyl_candidates_);
this->template cluster_candidates_base<Cone<T>>(cone_candidates_);
}
virtual void reset() {
plane_counter = 0;
svt.reset();
cyvt.reset();
covt.reset();
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::multimap<T, MyObject<T>*, std::greater<T>> candidate_map;
for (auto el : plane_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : sphere_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : cyl_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : cone_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
for (auto el : candidate_map) {
if (el.first > min_vote && sum_votes < max_points) {
candidates.push_back(el.second);
sum_votes += el.first;
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << plane_candidates_.size() << " plane candidates," << std::endl
<< sphere_candidates_.size() << " sphere candidates." << std::endl
<< cyl_candidates_.size() << " cylinder candidates." << std::endl
<< cone_candidates_.size() << " cone candidates." << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
os << "# planes:" << std::endl;
for (const auto el : plane_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# spheres:" << std::endl;
for (const auto el : sphere_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# cylinders:" << std::endl;
for (const auto el : cyl_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# cones:" << std::endl;
for (const auto el : cone_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
std::ofstream cone_file(folder + prefix + "_cones.txt");
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
if (Plane<T>* p = dynamic_cast<Plane<T>*>(obj)) {
plane_file << instance << "\t" << *p << std::endl;
}
else if (Sphere<T>* s = dynamic_cast<Sphere<T>*>(obj)) {
sphere_file << instance << "\t" << *s << std::endl;
}
else if (Cylinder<T>* c = dynamic_cast<Cylinder<T>*>(obj)) {
cyl_file << instance << "\t" << *c << std::endl;
}
else if (Cone<T>* c = dynamic_cast<Cone<T>*>(obj)) {
cone_file << instance << "\t" << *c << std::endl;
}
++instance;
}
plane_file.close();
sphere_file.close();
cyl_file.close();
cone_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // PRIMITIVE_DETECTOR_H_
| 16,306
|
C++
|
.h
| 336
| 38.482143
| 171
| 0.555668
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,819
|
PpfDetector.h
|
c-sommer_primitect/cpp/include/detector/PpfDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PPF_DETECTOR_H_
#define PPF_DETECTOR_H_
#include <iostream>
#include <bitset>
#include <Eigen/Dense>
#include "objects/MyObject.h"
struct DetectorSettings {
bool InterpolatedWeights = false; // 1, must be false for integer voting types
bool ClosenessWeights = false; // 2, must be false for integer voting types
bool MeanShift = false; // 4
bool PpfConditions = false; // 8
bool ApproximatedConditions = false; // 16
bool ClusterAveraging = false; // 32
DetectorSettings(bool InterpolatedWeights,
bool ClosenessWeights,
bool MeanShift,
bool PpfConditions,
bool ApproximatedConditions,
bool ClusterAveraging) :
InterpolatedWeights(InterpolatedWeights),
ClosenessWeights(ClosenessWeights),
MeanShift(MeanShift),
PpfConditions(PpfConditions),
ApproximatedConditions(ApproximatedConditions),
ClusterAveraging(ClusterAveraging)
{}
DetectorSettings(std::bitset<6> all) :
InterpolatedWeights(all[0]),
ClosenessWeights(all[1]),
MeanShift(all[2]),
PpfConditions(all[3]),
ApproximatedConditions(all[4]),
ClusterAveraging(all[5])
{}
void print() {
std::cout << "\tInterpolatedWeights:\t" << InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << ClosenessWeights << std::endl
<< "\tMeanShift:\t" << MeanShift << std::endl
<< "\tPpfConditions:\t" << PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << ClusterAveraging << std::endl;
}
};
template <class Pcd, typename T, typename VoteT>
class PpfDetector {
protected:
using Vec3 = Eigen::Matrix<T, 3, 1>;
using Vec4 = Eigen::Matrix<T, 4, 1>;
const T angle_bin_; // size of a bin in angular direction (in rad)
const T angle_bin_inv_;
const T cos_thresh_;
const T cos_thresh2_;
const T cos_thresh_half_;
const T sin_thresh_;
const T dist_bin_;
const T dist_bin_inv_;
const T min_dist_sq_;
const T dist_thresh_sq_;
const T max_param_;
const VoteT min_votes_ = 8; //2048, 8; 4096, 24
static Vec4 compute_cppf(Vec3 pr, Vec3 nr, Vec3 pi, Vec3 ni) {
Vec3 d = pi - pr;
Vec4 cppf;
cppf[0] = d.squaredNorm();
cppf[1] = d.dot(nr);
cppf[2] = d.dot(ni);
cppf[3] = nr.dot(ni);
return cppf;
}
static Vec4 compute_ppf(Vec4 cppf) {
Vec4 ppf;
ppf[0] = std::sqrt(cppf[0]);
T ppf0_inv = 1. / ppf[0];
ppf[1] = std::acos(cppf[1] * ppf0_inv);
ppf[2] = std::acos(cppf[2] * ppf0_inv);
ppf[3] = std::acos(cppf[3]);
return ppf;
}
Vec3 pr_, nr_;
Eigen::Matrix<T, 2, 3> rot_;
virtual void pair_vote(Vec4 cppf, Vec3 pi, Vec3 ni) = 0;
virtual void add_candidate(Vec3 pr, Vec3 nr) = 0;
DetectorSettings settings_;
public:
PpfDetector(DetectorSettings settings, T angle_bin = 10. * M_PI / 180., T dist_bin = 0.025) :
settings_(settings),
angle_bin_(angle_bin),
angle_bin_inv_(1. / angle_bin),
cos_thresh_(std::cos(angle_bin)),
cos_thresh2_(std::cos(2 * angle_bin)),
cos_thresh_half_(std::cos(.5 * angle_bin)),
sin_thresh_(std::sin(angle_bin)),
dist_bin_(dist_bin),
dist_bin_inv_(1. / dist_bin),
min_dist_sq_(64 * dist_bin * dist_bin),
dist_thresh_sq_(1.0),
max_param_(1.0)
{
correct_settings();
}
PpfDetector(DetectorSettings settings, T diameter, bool is_scene, T angle_bin = 10. * M_PI / 180.) :
settings_(settings),
angle_bin_(angle_bin),
angle_bin_inv_(1. / angle_bin),
cos_thresh_(std::cos(angle_bin)),
cos_thresh2_(std::cos(2 * angle_bin)),
cos_thresh_half_(std::cos(.5 * angle_bin)),
sin_thresh_(std::sin(angle_bin)),
dist_bin_(is_scene ? .005 * diameter : .01 * diameter),
dist_bin_inv_(1. / dist_bin_),
min_dist_sq_(.0016 * diameter * diameter),
dist_thresh_sq_(is_scene ? .04 * diameter * diameter : .16 * diameter * diameter),
max_param_(is_scene ? .2 * diameter : .5 * diameter)
{
correct_settings();
}
void correct_settings() {
if (std::is_integral<T>::value) { // if voting type is integer, weighted voting does not make sense
settings_.InterpolatedWeights = false;
settings_.ClosenessWeights = false;
}
if (settings_.PpfConditions || settings_.ClosenessWeights) { // only CPPF conditions can be approximated in a meaningful way
settings_.ApproximatedConditions = false;
}
}
virtual ~PpfDetector() {}
virtual void cast_votes(Pcd& pc) {
size_t num_points = pc.num_points();
for (size_t r = 0; r < num_points; ++r) { // reference point
if (!set_rot(pc.normal(r))) {
continue;
}
pr_ = pc.point(r);
nr_ = pc.normal(r);
for (size_t i = 0; i < num_points; ++i) { // pair point
if (i == r)
continue;
Vec4 cppf = compute_cppf(pr_, nr_, pc.point(i), pc.normal(i));
if (cppf[0] < dist_thresh_sq_)
pair_vote(cppf, pc.point(i), pc.normal(i));
}
add_candidate(pr_, nr_);
reset();
}
}
template <class Object>
void cluster_candidates_base(std::multimap<T, Object*, std::greater<T>>& candidates) {
static_assert(std::is_base_of<MyObject<T>, Object>::value, "Object must be derived from MyObject<T>"); // make sure Object is of type MyObject<T>
bool ClusterAveraging = settings_.ClusterAveraging;
std::multimap<T, Object*, std::greater<T>> new_candidates;
for (auto it = candidates.begin(); it != candidates.end(); ++it) {
Object* Oi = it->second;
T wcurr = it->first;
for (auto jt = std::next(it); jt != candidates.end();) {
Object* Oj = jt->second;
if (Oi->are_similar(Oj, .1)) {
if (ClusterAveraging) // if false: simple non-maximum suppression
wcurr = Oi->integrate(wcurr, Oj, jt->first);
else
wcurr += jt->first;
jt = candidates.erase(jt);
} else {
++jt;
}
}
new_candidates.emplace(wcurr, Oi);
}
candidates = new_candidates;
return;
}
virtual void cluster_candidates() = 0;
virtual void reset() = 0;
void set_settings(DetectorSettings settings) {
settings_ = settings;
}
bool set_rot(Vec3 nr) {
const T nx1_inv = 1. / (1. + nr[0]);
if (!std::isfinite(nx1_inv)) {
return false;
}
rot_(0,0) = -nr[1];
rot_(1,0) = -nr[2];
rot_(0,1) = 1. - nr[1] * nr[1] * nx1_inv;
rot_(1,1) = -nr[1] * nr[2] * nx1_inv;
rot_(0,2) = rot_(1,1);
rot_(1,2) = 1. - nr[2] * nr[2] * nx1_inv;
return true;
}
virtual void print_votes() const {
std::cout << "Votes cannot be printed (yet), sorry." << std::endl;
}
virtual void print_parameters(Vec3 pr, Vec3 nr) const {
std::cout << "This functionality is not (yet) implemented, sorry." << std::endl;
}
virtual void print_info() const = 0;
virtual void write_candidates(std::ostream& os) const = 0;
virtual void print_candidates(const int threshold = 0) const {
write_candidates(std::cout);
}
virtual void candidates_to_file(std::string filename, const int threshold = 0) const {
std::ofstream outfile(filename);
write_candidates(outfile);
outfile.close();
}
virtual void write_results(const std::string folder, std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const = 0;
};
#endif // PPF_DETECTOR_H_
| 9,555
|
C++
|
.h
| 227
| 33.207048
| 166
| 0.587229
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,820
|
PlaneConeDetector.h
|
c-sommer_primitect/cpp/include/detector/PlaneConeDetector.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef PLANE_CONE_DETECTOR_H_
#define PLANE_CONE_DETECTOR_H_
#include <iostream>
#include <fstream>
#include <map>
#include <Eigen/Dense>
#include "PpfDetector.h"
#include "ConeVotingTable.h"
#include "objects/Cone.h"
template <class Pcd, typename T, typename VoteT>
class PlaneConeDetector : public PpfDetector<Pcd, T, VoteT> {
using typename PpfDetector<Pcd, T, VoteT>::Vec3;
using typename PpfDetector<Pcd, T, VoteT>::Vec4;
static T axis_dist(Vec4 cppf) {
return cppf[2] / (1. - cppf[3]);
}
Vec3 axis(Vec4 cppf, Vec3 pi, Vec3 ni) {
Vec3 a = this->pr_ - pi + (cppf[2] * this->nr_ + cppf[1] * ni) / (cppf[3] - 1.);
return a.normalized();
}
VoteT plane_counter = 0;
ConeVotingTable<T, VoteT> cvt;
std::multimap<T, Plane<T>*, std::greater<T>> plane_candidates_;
std::multimap<T, Cone<T>*, std::greater<T>> cone_candidates_;
virtual void pair_vote(Vec4 cppf, Vec3 pi, Vec3 ni) { // conditions: normals not parallel, feature symmetric, vectors form triangle
DetectorSettings& s = this->settings_;
if (cppf[3] >= this->cos_thresh_) { // if normals are approximately parallel, no cone voting
if (cppf[0] < this->min_dist_sq_) // distance between points to small to distinguish plane from cylinder/cone
return;
if (std::abs(cppf[1]) > this->dist_bin_ || std::abs(cppf[2]) > this->dist_bin_) // points too far from other plane
return;
// this already includes |angle(n, d) - pi/2| < angle_bin_
// if sin(angle_bin_) * 10 > 1
// which is true if angle_bin_ > 5.74° (so we require angle_bin_ >= 6° to be on the safe side)
if (!s.ClosenessWeights) {
if (cppf[3] >= this->cos_thresh_half_)
++plane_counter;
}
else {
T bin_inv = this->angle_bin_inv_;
T d_inv = 1. / std::sqrt(cppf[0]);
T weight = (1. - std::acos(cppf[3]) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[1] * d_inv)) * bin_inv);
weight *= (1. - std::abs(std::asin(cppf[2] * d_inv)) * bin_inv);
plane_counter += weight;
}
return;
}
if (cppf[1] > 0 || cppf[2] < 0) // "quadrant/octant conditions" - possibly extend by sin_thresh or so?
return;
T dist = axis_dist(cppf);
// Vec3 a = axis(cppf, pi, ni);
// T sin_t = std::abs(a.dot(this->nr_));
// dist = (1. - sin_t * sin_t) * dist / sin_t;
if (cvt.not_valid(dist))
return;
// do not impose any anti-degeneracy conditions
cvt.vote(dist, axis(cppf, pi, ni), s.InterpolatedWeights);
}
virtual void add_candidate(Vec3 pr, Vec3 nr) {
using Vec2 = Eigen::Matrix<T, 2, 1>;
std::pair<VoteT, Vec4> el = cvt.get_dist_axis(this->settings_.MeanShift);
VoteT cone_votes = el.first;
if (cone_votes > plane_counter) {
T dist = el.second[0];
Vec3 a(el.second[1], el.second[2], el.second[3]);
Vec3 c = pr + dist * (a / a.dot(nr) - nr);
a = (a.dot(pr - c) > 0) ? a : -a;
T sin_theta = -a.dot(nr);
// T sin_theta = a.dot(nr);
// a = sin_theta > 0 ? -a : a;
// sin_theta = std::abs(sin_theta);
// Vec3 c = pr - dist * (a + sin_theta * nr) / (1 - sin_theta * sin_theta);
// discard if opening angle too small (i.e. close to cylinder), or too large (i.e. close to plane)
// but should not actually be necessary since these options are already excluded --> TODO: investigate/debug!
if (sin_theta < .5*this->sin_thresh_ || sin_theta > this->cos_thresh2_)
return;
cone_candidates_.emplace(cone_votes, new Cone<T>(c, a, sin_theta, pr));
}
else if (plane_counter > this->min_votes_) {
plane_candidates_.emplace(plane_counter, new Plane<T>(nr, -nr.dot(pr), pr));
}
}
public:
PlaneConeDetector(DetectorSettings settings = DetectorSettings(false, false, false, false, false, false), T Dmax = 1.) :
PpfDetector<Pcd, T, VoteT>(settings),
cvt(ConeVotingTable<T, VoteT>(Dmax, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
PlaneConeDetector(T diameter, bool is_scene, DetectorSettings settings = DetectorSettings(false, false, false, false, false, false)) :
PpfDetector<Pcd, T, VoteT>(settings, diameter, is_scene),
cvt(ConeVotingTable<T, VoteT>(this->max_param_, this->dist_bin_, this->angle_bin_))
{
cvt.set_threshold(this->min_votes_);
}
virtual ~PlaneConeDetector() {
for (auto& el : plane_candidates_) {
delete el.second;
}
for (auto& el : cone_candidates_) {
delete el.second;
}
}
virtual void cluster_candidates() {
this->template cluster_candidates_base<Plane<T>>(plane_candidates_);
this->template cluster_candidates_base<Cone<T>>(cone_candidates_);
}
virtual void reset() {
plane_counter = 0;
cvt.reset();
}
virtual std::vector<MyObject<T>*> candidate_vector(const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::multimap<T, MyObject<T>*, std::greater<T>> candidate_map;
for (auto el : plane_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
for (auto el : cone_candidates_) {
candidate_map.emplace(std::sqrt(el.first), static_cast<MyObject<T>*>(el.second));
}
std::vector<MyObject<T>*> candidates;
T sum_votes = 0;
for (auto el : candidate_map) {
if (el.first > min_vote && sum_votes < max_points) {
candidates.push_back(el.second);
sum_votes += el.first;
}
else
break;
}
return candidates;
}
virtual void print_info() const {
std::cout << plane_candidates_.size() << " plane candidates," << std::endl
<< cone_candidates_.size() << " cone candidates." << std::endl;
}
virtual void write_candidates(std::ostream& os) const {
os << "# planes:" << std::endl;
for (const auto el : plane_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
os << "# cones:" << std::endl;
for (const auto el : cone_candidates_) {
os << el.first << "\t" << *(el.second) << std::endl;
}
}
virtual void write_results(const std::string folder, const std::string filename, const T min_vote = 0, const T max_points = std::numeric_limits<T>::infinity()) const {
std::string prefix = filename.substr(0, filename.size() - 4);
std::ofstream plane_file(folder + prefix + "_planes.txt");
std::ofstream sphere_file(folder + prefix + "_spheres.txt");
sphere_file.close();
std::ofstream cyl_file(folder + prefix + "_cylinders.txt");
cyl_file.close();
std::ofstream cone_file(folder + prefix + "_cones.txt");
std::vector<MyObject<T>*> candidates = candidate_vector(min_vote, max_points); // add second argument!!
size_t instance = 1;
for (const auto& obj : candidates) {
if (Plane<T>* p = dynamic_cast<Plane<T>*>(obj)) {
plane_file << instance << "\t" << *p << std::endl;
}
else if (Cone<T>* c = dynamic_cast<Cone<T>*>(obj)) {
cone_file << instance << "\t" << *c << std::endl;
}
++instance;
}
plane_file.close();
cone_file.close();
// write settings to file
std::ofstream outfile(folder + prefix + "_settings.txt");
const DetectorSettings& s = this->settings_;
outfile << "\tInterpolatedWeights:\t" << s.InterpolatedWeights << std::endl
<< "\tClosenessWeights:\t" << s.ClosenessWeights << std::endl
<< "\tMeanShift:\t" << s.MeanShift << std::endl
<< "\tPpfConditions:\t" << s.PpfConditions << std::endl
<< "\tApproximatedConditions:\t" << s.ApproximatedConditions << std::endl
<< "\tClusterAveraging:\t" << s.ClusterAveraging << std::endl;
outfile.close();
}
};
#endif // CONE_DETECTOR_H_
| 9,711
|
C++
|
.h
| 199
| 39.643216
| 171
| 0.58019
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,821
|
optimizers.h
|
c-sommer_primitect/cpp/include/shapefit/optimizers.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "shapefit/PlaneOptimizer.h"
#include "shapefit/SphereOptimizer.h"
#include "shapefit/CylinderOptimizer.h"
#include "shapefit/ConeOptimizer.h"
| 1,119
|
C++
|
.h
| 23
| 47.391304
| 101
| 0.809174
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,822
|
ConeOptimizer.h
|
c-sommer_primitect/cpp/include/shapefit/ConeOptimizer.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "ShapeOptimizer.h"
#include "objects/Cone.h"
#include "LocalParamS2.h"
#include "LocalParamTheta.h"
/**
* cost function for Ceres optimization of Cone parameters
* due to if-condition in residual computation, automatic differentiation is not straightforward
*/
class ConeCostFunction : public ceres::SizedCostFunction<1, 3, 3, 3> {
Eigen::Vector3d p_;
public:
ConeCostFunction(Eigen::Vector3f p) :
ceres::SizedCostFunction<1, 3, 3, 3>(),
p_(p.cast<double>())
{}
virtual ~ConeCostFunction() {}
virtual bool Evaluate(double const* const* parameters,
double* residual,
double** jacobians) const {
const double* c = parameters[0];
const double* a = parameters[1];
const double* theta3 = parameters[2];
const double dx = p_[0] - c[0];
const double dy = p_[1] - c[1];
const double dz = p_[2] - c[2];
const double d_sq = dx * dx + dy * dy + dz * dz;
const double h = dx * a[0] + dy * a[1] + dz * a[2];
const double r = std::sqrt(d_sq - h * h);
if (h * theta3[1] + r * theta3[0] < 0.) {
residual[0] = - std::sqrt(d_sq);
if (jacobians && jacobians[0]) {
// derivatives w.r.t. c
const double d_inv = - 1. / residual[0];
jacobians[0][0] = dx * d_inv;
jacobians[0][1] = dy * d_inv;
jacobians[0][2] = dz * d_inv;
// derivatives w.r.t. a are zero
jacobians[1][0] = jacobians[1][1] = jacobians[1][2] = 0.;
// derivatives w.r.t. theta3 are zero
jacobians[2][0] = jacobians[2][1] = jacobians[2][2] = 0.;
}
}
else {
residual[0] = h * theta3[0] - r * theta3[1];
if (jacobians && jacobians[0]) {
const double r_inv = 1. / r;
const double coeff = theta3[0] + h * r_inv * theta3[1];
// derivatives w.r.t. c
jacobians[0][0] = - coeff * a[0] + theta3[1] * r_inv * dx;
jacobians[0][1] = - coeff * a[1] + theta3[1] * r_inv * dy;
jacobians[0][2] = - coeff * a[2] + theta3[1] * r_inv * dz;
// derivatives w.r.t. a
jacobians[1][0] = coeff * dx;
jacobians[1][1] = coeff * dy;
jacobians[1][2] = coeff * dz;
// derivatives w.r.t. theta3
jacobians[2][0] = h;
jacobians[2][1] = -r;
jacobians[2][2] = 0.;
}
}
return true;
}
};
/*
* actual Cone optimizer class
*/
template <class Pcd>
class ConeOptimizer : public ShapeOptimizer<Pcd> {
Cone<double>* C_;
virtual void add_residual(Eigen::Vector3f point) {
// ConeResidual* res = new ConeResidual(point);
// ceres::CostFunction* cost = new ceres::AutoDiffCostFunction<ConeResidual, 1, 3, 3, 3>(res);
ceres::CostFunction* cost = new ConeCostFunction(point);
double* params = C_->data();
this->problem_->AddResidualBlock(cost, new TruncatedLoss(this->scale_), &(params[0]), &(params[3]), &(params[6]));
}
virtual void set_param() {
this->problem_->SetParameterization(&(C_->data()[3]), new LocalParamS2);
this->problem_->SetParameterization(&(C_->data()[6]), new LocalParamTheta);
}
public:
ConeOptimizer(Cone<double>* C) :
C_(C)
{}
};
| 4,561
|
C++
|
.h
| 105
| 34.533333
| 122
| 0.587046
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,823
|
PlaneOptimizer.h
|
c-sommer_primitect/cpp/include/shapefit/PlaneOptimizer.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "ShapeOptimizer.h"
#include "objects/Plane.h"
#include "LocalParamS2.h"
/**
* residual for Ceres optimization of Plane parameters
*/
struct PlaneResidual {
PlaneResidual(Eigen::Vector3f p) :
p_(p.cast<double>())
{}
template <typename T>
bool operator()(const T* n, const T* d, T* residual) const {
residual[0] = n[0] * p_[0] + n[1] * p_[1] + n[2] * p_[2] + d[0];
return true;
}
private:
Eigen::Vector3d p_;
};
/*
* actual Plane optimizer class
*/
template <class Pcd>
class PlaneOptimizer : public ShapeOptimizer<Pcd> {
Plane<double>* P_;
virtual void add_residual(Eigen::Vector3f point) {
PlaneResidual* res = new PlaneResidual(point);
ceres::CostFunction* cost = new ceres::AutoDiffCostFunction<PlaneResidual, 1, 3, 1>(res);
this->problem_->AddResidualBlock(cost, new TruncatedLoss(this->scale_), P_->data(), &(P_->data()[3]));
}
virtual void set_param() {
this->problem_->SetParameterization(P_->data(), new LocalParamS2);
}
public:
PlaneOptimizer(Plane<double>* P) :
P_(P)
{}
};
| 2,130
|
C++
|
.h
| 56
| 33.892857
| 112
| 0.710074
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,824
|
SphereOptimizer.h
|
c-sommer_primitect/cpp/include/shapefit/SphereOptimizer.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "ShapeOptimizer.h"
#include "objects/Sphere.h"
/**
* residual for Ceres optimization of sphere parameters
*/
struct SphereResidual {
SphereResidual(Eigen::Vector3f p) :
p_(p.cast<double>())
{}
template <typename T>
bool operator()(const T* cr, T* residual) const {
const T dx = cr[0] - p_[0];
const T dy = cr[1] - p_[1];
const T dz = cr[2] - p_[2];
const T dist_to_center = ceres::sqrt(dx * dx + dy * dy + dz * dz);
residual[0] = dist_to_center - cr[3];
return true;
}
private:
Eigen::Vector3d p_;
};
/*
* actual sphere optimizer class
*/
template <class Pcd>
class SphereOptimizer : public ShapeOptimizer<Pcd> {
Sphere<double>* S_;
virtual void add_residual(Eigen::Vector3f point) {
SphereResidual* res = new SphereResidual(point);
ceres::CostFunction* cost = new ceres::AutoDiffCostFunction<SphereResidual, 1, 4>(res);
this->problem_->AddResidualBlock(cost, new TruncatedLoss(this->scale_), S_->data());
}
public:
SphereOptimizer(Sphere<double>* S) :
S_(S)
{}
};
| 2,151
|
C++
|
.h
| 56
| 33.571429
| 101
| 0.704668
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,825
|
ShapeOptimizer.h
|
c-sommer_primitect/cpp/include/shapefit/ShapeOptimizer.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <Eigen/Dense>
#include <ceres/ceres.h>
// folder includes
#include "TruncatedLoss.h"
// function includes
#include "pcd/PointCloudData.h"
template <class Pcd>
class ShapeOptimizer {
const double median_mult_ = 4.;
const double initial_scale_ = 0.05;
// approximate median computation (enough for our purpose)
static double median(std::vector<double>& vec) {
size_t n = vec.size();
if (n < 2) {
return 0;
}
else {
std::nth_element(vec.begin(), vec.begin() + n / 2, vec.end());
return vec[n / 2];
}
}
// compute right scale for ceres::LossFunction
void recompute_scale() {
std::vector<double> residuals, abs_residuals;
ceres::Problem::EvaluateOptions options;
options.apply_loss_function = false;
problem_->Evaluate(options, nullptr, &residuals, nullptr, nullptr);
if (residuals.size() < 3) {
return;
}
for (const auto& r : residuals) {
double r_abs = std::abs(r);
if (r_abs < scale_)
abs_residuals.push_back(r_abs);
}
scale_ = median_mult_ * median(abs_residuals);
}
protected:
ceres::Problem* problem_;
double scale_ = initial_scale_;
virtual void add_residual(Eigen::Vector3f point) = 0;
virtual void set_param() {}
public:
bool optimize(const Pcd& pc) {
// set up solver
ceres::Solver::Options options;
options.max_num_iterations = 5;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = false;//true;
ceres::Solver::Summary summary;
for (size_t outer=0; outer<25; ++outer) {
// set up problem
problem_ = new ceres::Problem;
for (size_t idx=0; idx<pc.num_points(); ++idx) {
add_residual(pc.point(idx));
}
set_param();
// solve problem
ceres::Solve(options, problem_, &summary);
// std::cout << "Current scale: " << scale_ << std::endl;
// std::cout << summary.BriefReport() << std::endl; // BriefReport or FullReport
if (summary.num_successful_steps < 2) {
delete problem_;
break;
}
recompute_scale();
delete problem_;
}
std::cout << "Scale: " << scale_ << ", convergence: " << (summary.termination_type == ceres::CONVERGENCE) << std::endl;
if (scale_ > 0.04 || summary.termination_type == ceres::NO_CONVERGENCE) {
scale_ = initial_scale_;
return false;
}
scale_ = initial_scale_;
return true;
}
};
| 3,863
|
C++
|
.h
| 97
| 31.43299
| 127
| 0.624827
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,826
|
CylinderOptimizer.h
|
c-sommer_primitect/cpp/include/shapefit/CylinderOptimizer.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "ShapeOptimizer.h"
#include "objects/Cylinder.h"
#include "LocalParamGraff13.h"
/**
* residual for Ceres optimization of cylinder parameters
*/
struct CylinderResidual {
CylinderResidual(Eigen::Vector3f p) :
p_(p.cast<double>())
{}
template <typename T>
bool operator()(const T* ca, const T* r, T* residual) const {
const T dx = ca[0] - p_[0];
const T dy = ca[1] - p_[1];
const T dz = ca[2] - p_[2];
const T dTa = dx * ca[3] + dy * ca[4] + dz * ca[5];
const T dist_to_center = ceres::sqrt(dx * dx + dy * dy + dz * dz - dTa * dTa);
residual[0] = dist_to_center - r[0];
return true;
}
private:
Eigen::Vector3d p_;
};
/*
* actual Cylinder optimizer class
*/
template <class Pcd>
class CylinderOptimizer : public ShapeOptimizer<Pcd> {
Cylinder<double>* C_;
virtual void add_residual(Eigen::Vector3f point) {
CylinderResidual* res = new CylinderResidual(point);
ceres::CostFunction* cost = new ceres::AutoDiffCostFunction<CylinderResidual, 1, 6, 1>(res);
this->problem_->AddResidualBlock(cost, new TruncatedLoss(this->scale_), C_->data(), &(C_->data()[6]));
}
virtual void set_param() {
this->problem_->SetParameterization(C_->data(), new LocalParamGraff13);
}
public:
CylinderOptimizer(Cylinder<double>* C) :
C_(C)
{}
};
| 2,430
|
C++
|
.h
| 61
| 34.868852
| 112
| 0.694444
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,827
|
LocalParamGraff13.h
|
c-sommer_primitect/cpp/include/shapefit/LocalParamGraff13.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef LOCAL_PARAM_GRAFF13_H_
#define LOCAL_PARAM_GRAFF13_H_
#include <ceres/local_parameterization.h>
class LocalParamGraff13 : public ceres::LocalParameterization {
public:
LocalParamGraff13() {}
virtual ~LocalParamGraff13() {}
// Graff13 plus operation for Ceres
//
virtual bool Plus(double const* ca, double const* delta,
double* ca_plus_delta) const { // ca: c (point on axis), a (axis direction)
const double norm_inv = 1. / std::sqrt(1. + delta[2]*delta[2] + delta[3]*delta[3]);
ca_plus_delta[0] = ca[0] - ca[4] * delta[0] - ca[5] * delta[1];
ca_plus_delta[3] = (ca[3] - ca[4] * delta[2] - ca[5] * delta[3]) * norm_inv;
const double a_x_dc = (ca[5] * delta[0] - ca[4] * delta[1]);
const double a_x_da = (ca[5] * delta[2] - ca[4] * delta[3]);
if (ca[3] > 0.) { // ca[3] = a[x]
const double ax1_inv = 1. / (1. + ca[3]);
ca_plus_delta[1] = ca[1] + ca[3] * delta[0] + ax1_inv * a_x_dc * ca[5];
ca_plus_delta[2] = ca[2] + ca[3] * delta[1] - ax1_inv * a_x_dc * ca[4];
ca_plus_delta[4] = (ca[4] + ca[3] * delta[2] + ax1_inv * a_x_da * ca[5]) * norm_inv;
ca_plus_delta[5] = (ca[5] + ca[3] * delta[3] - ax1_inv * a_x_da * ca[4]) * norm_inv;
}
else {
const double ax1_inv = 1. / (1. - ca[3]);
ca_plus_delta[1] = ca[1] + ca[3] * delta[0] - ax1_inv * a_x_dc * ca[5];
ca_plus_delta[2] = ca[2] + ca[3] * delta[1] + ax1_inv * a_x_dc * ca[4];
ca_plus_delta[4] = (ca[4] + ca[3] * delta[2] - ax1_inv * a_x_da * ca[5]) * norm_inv;
ca_plus_delta[5] = (ca[5] + ca[3] * delta[3] + ax1_inv * a_x_da * ca[4]) * norm_inv;
}
return true;
}
// Jacobian of Graff13 plus operation for Ceres
//
virtual bool ComputeJacobian(double const* ca,
double* J) const {
// Jacobian has size 6x4, row-major
// Jacobian is block diagonal: upper left and lower right 3x2 blocks are 2nd and 3rd cols of R^T, rest is zero
J[2] = J[3] = J[6] = J[7] = J[10] = J[11] = 0.;
J[12] = J[13] = J[16] = J[17] = J[20] = J[21] = 0.;
J[0] = J[14] = -ca[4];
J[1] = J[15] = -ca[5];
if (ca[3] > 0.) { // ca[3] = a[x]
const double ax1_inv = 1. / (1. + ca[3]);
// Jacobian has size 3x2
J[4] = J[18] = ca[3] + ax1_inv * ca[5] * ca[5];
J[5] = J[19] = -ax1_inv * ca[4] * ca[5];
J[8] = J[22] = J[5];
J[9] = J[23] = ca[3] + ax1_inv * ca[4] * ca[4];
}
else {
const double ax1_inv = 1. / (1. - ca[3]);
// Jacobian has size 3x2
J[4] = J[18] = ca[3] - ax1_inv * ca[5] * ca[5];
J[5] = J[19] = ax1_inv * ca[4] * ca[5];
J[8] = J[22] = J[5];
J[9] = J[23] = ca[3] - ax1_inv * ca[4] * ca[4];
}
return true;
}
virtual int GlobalSize() const { return 6; }
virtual int LocalSize() const { return 4; }
};
#endif // LOCAL_PARAM_GRAFF13_H_
| 4,156
|
C++
|
.h
| 83
| 41.614458
| 118
| 0.554304
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,828
|
LocalParamTheta.h
|
c-sommer_primitect/cpp/include/shapefit/LocalParamTheta.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#ifndef LOCAL_PARAM_THETA_H_
#define LOCAL_PARAM_THETA_H_
#include <ceres/local_parameterization.h>
class LocalParamTheta : public ceres::LocalParameterization {
static constexpr double PI_2 = .5 * M_PI;
public:
LocalParamTheta() {}
virtual ~LocalParamTheta() {}
// Theta plus operation for Ceres
//
virtual bool Plus(double const* theta3, double const* delta,
double* theta3_plus_delta) const {
const double theta_plus_delta = theta3[2] + delta[0];
// TODO: possibly truncate theta to [0, pi/2]
theta3_plus_delta[0] = std::sin(theta_plus_delta);
theta3_plus_delta[1] = std::sqrt(1. - theta3_plus_delta[0] * theta3_plus_delta[0]);
theta3_plus_delta[2] = theta_plus_delta;
return true;
}
// Jacobian of Theta plus operation for Ceres
//
virtual bool ComputeJacobian(double const* theta3,
double* J) const {
// Jacobian has size 3x1
J[0] = theta3[1];
J[1] = -theta3[0];
J[2] = 1.;
return true;
}
virtual int GlobalSize() const { return 3; }
virtual int LocalSize() const { return 1; }
};
#endif // LOCAL_PARAM_THETA_H_
| 2,248
|
C++
|
.h
| 52
| 37.057692
| 101
| 0.699811
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,829
|
TruncatedLoss.h
|
c-sommer_primitect/cpp/include/shapefit/TruncatedLoss.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include <ceres/ceres.h>
class TruncatedLoss : public ceres::LossFunction {
const double scale_sq_;
public:
TruncatedLoss(double scale = 1.) :
scale_sq_(scale * scale)
{}
virtual void Evaluate(double res_sq, double out[3]) const {
if (res_sq < scale_sq_) {
out[0] = res_sq;
out[1] = 1.;
out[2] = 0.;
}
else {
out[0] = scale_sq_;
out[1] = 0.;
out[2] = 0.;
}
return;
}
};
| 1,487
|
C++
|
.h
| 40
| 32.3
| 101
| 0.691986
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,831
|
detection_metrics.h
|
c-sommer_primitect/cpp/track_object/detection_metrics.h
|
/**
GPL (v3+) License
This file is part of the code accompanying the paper
PrimiTect: Fast Continuous Hough Voting for Primitive Detection
by C. Sommer, Y. Sun, E. Bylow and D. Cremers,
accepted for publication in the IEEE International Conference on Robotics and Automation (ICRA) 2020.
Copyright (c) 2019, Christiane Sommer.
All rights reserved.
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 3 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, see <https://www.gnu.org/licenses/>.
*/
#include "pcd/PointCloudData.h"
#include "objects/MyObject.h"
template <class Pcd, typename T>
size_t metric_inliers(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
size_t counter = 0;
size_t N = pc.num_points();
for (size_t idx=0; idx<N; ++idx) {
T psi = O->sdf(pc.point(idx).template cast<T>());
if (std::abs(psi) < threshold) {
T weight = pc.normal(idx).template cast<T>().dot(O->normal(pc.point(idx).template cast<T>()));
if (weight * weight > .95) {
++counter;
}
}
}
return counter;
}
template <class Pcd, typename T>
T metric_coverage(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
return metric_inliers(pc, O, threshold) / static_cast<T>(pc.num_points());
}
template <class Pcd, typename T>
T metric_rms(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
T sum = 0.;
size_t counter = 0;
size_t N = pc.num_points();
for (size_t idx=0; idx<N; ++idx) {
T psi = O->sdf(pc.point(idx).template cast<T>());
if (psi > -threshold && psi < threshold) {
T weight = pc.normal(idx).template cast<T>().dot(O->normal(pc.point(idx).template cast<T>()));
if (weight * weight > .95) {
sum += psi * psi;
++counter;
}
}
}
if (counter<1) {
return 0;
}
return std::sqrt(sum / counter);
}
template <class Pcd, typename T>
T metric_mean(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
T sum = 0.;
size_t counter = 0;
size_t N = pc.num_points();
for (size_t idx=0; idx<N; ++idx) {
T psi = std::abs(O->sdf(pc.point(idx).template cast<T>()));
if (psi < threshold) {
T weight = pc.normal(idx).template cast<T>().dot(O->normal(pc.point(idx).template cast<T>()));
if (weight * weight > .95) {
sum += psi;
++counter;
}
}
}
if (counter<1) {
return 0.;
}
return sum / counter;
}
template <class Pcd, typename T>
T metric_p80(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
T sum = 0.;
std::vector<T> residuals;
size_t N = pc.num_points();
for (size_t idx=0; idx<N; ++idx) {
T psi = std::abs(O->sdf(pc.point(idx).template cast<T>()));
if (psi < threshold) {
T weight = pc.normal(idx).template cast<T>().dot(O->normal(pc.point(idx).template cast<T>()));
if (weight * weight > .95) {
residuals.push_back(psi);
}
}
}
if (residuals.size()<1) {
return 0.;
}
size_t idx = static_cast<size_t>(.80 * residuals.size());
std::nth_element(residuals.begin(), residuals.begin() + idx, residuals.end());
return residuals[idx];
}
template <class Pcd, typename T>
void print_metrics(const Pcd& pc, MyObject<T>* O, const T threshold = 0.05) {
std::cout << "Inliers:\t" << metric_inliers<Pcd, T>(pc, O) << "\t"
<< "Coverage:\t" << metric_coverage<Pcd, T>(pc, O) * 100 << "\%\t"
<< "80th percentile:\t" << metric_p80<Pcd, T>(pc, O) << "\t"
<< "mean:\t" << metric_mean<Pcd, T>(pc, O) << "\t"
<< "RMS:\t" << metric_rms<Pcd, T>(pc, O) << std::endl;
return;
}
| 4,348
|
C++
|
.h
| 110
| 32.863636
| 106
| 0.599952
|
c-sommer/primitect
| 31
| 10
| 1
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,833
|
main.cpp
|
drlukeparry_libSLM/main.cpp
|
#include <math.h>
#include <iostream>
#include <App/Header.h>
#include <Translators/EOS/Reader.h>
#include <Translators/EOS/Writer.h>
#include <Translators/MTT/Reader.h>
#include <Translators/MTT/Writer.h>
#include <Translators/Realizer/Reader.h>
#include <Translators/Realizer/Writer.h>
#include <Translators/SLMSOL/Reader.h>
#include <Translators/SLMSOL/Writer.h>
int main(int argc, char *argv[])
{
if(argc < 2) {
std::cerr << "Number of argument must be one ";
}
std::string path = argv[0];
std::string mode = argv[1];
std::string inputFilename = argv[2];
std::string outputFilename = argv[3];
std::cout << "Reading file " << inputFilename << std::endl;
if(mode.find("mtt") != std::string::npos) {
slm::MTT::Reader reader(inputFilename);
std::cout << "Parsing File" << std::endl;
reader.parse();
slm::MTT::Writer writer(outputFilename);
slm::Header header;
header.zUnit = reader.getZUnit();
header.vMajor = 1;
header.vMinor = 6;
header.fileName = "MTT Layerfile";
writer.write(header, reader.getModels(), reader.getLayers());
} else if(mode.find("realizer") != std::string::npos) {
slm::realizer::Reader reader(inputFilename);
std::cout << "Parsing File" << std::endl;
reader.parse();
slm::realizer::Writer writer(outputFilename);
slm::Header header;
header.zUnit = 1000;
header.vMajor = 4;
header.vMinor = 7;
header.fileName = outputFilename;
std::string headerStr = reader.getHeader();
writer.setHeaderText(headerStr);
writer.write(header, reader.getModels(), reader.getLayers());
} else if(mode.find("eos") != std::string::npos) {
slm::eos::Reader reader(inputFilename);
std::cout << "Parsing File" << std::endl;
reader.parse();
slm::eos::Writer writer(outputFilename);
slm::Header header;
header.zUnit = 1000;
header.vMajor = 4;
header.vMinor = 7;
header.fileName = outputFilename;
float sf = reader.getScaleFactor();
writer.setScaleFactor(sf);
writer.write(header, reader.getModels(), reader.getLayers());
} else {
std::cerr << "Error: Invalid option given";
}
}
| 2,347
|
C++
|
.cpp
| 62
| 30.790323
| 69
| 0.63118
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,834
|
module.cpp
|
drlukeparry_libSLM/python/libSLM/module.cpp
|
#include <string>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <pybind11/functional.h>
#include <pybind11/complex.h>
#include <pybind11/eigen.h>
#include <tuple>
#include <App/Header.h>
#include <App/Layer.h>
#include <App/Model.h>
#include <App/Reader.h>
#include <App/Writer.h>
#include "utils.h"
namespace py = pybind11;
using namespace slm;
PYBIND11_MAKE_OPAQUE(std::vector<slm::LayerGeometry::Ptr>)
PYBIND11_MAKE_OPAQUE(std::vector<slm::BuildStyle::Ptr>)
PYBIND11_MODULE(slm, m) {
m.doc() = R"pbdoc(
PySLM Support Module
-----------------------
.. currentmodule:: slm
.. autosummary::
:toctree: _generate
)pbdoc";
#if 1
/*
* Create a trampolise class for slm::Reader as this contains a pure virtual function
*/
class PyReader : public slm::base::Reader {
public:
/* Inherit the constructors */
using slm::base::Reader::Reader;
/* Trampoline (need one for each virtual function) */
int parse() override {
PYBIND11_OVERRIDE_PURE(
int, /* Return type */
Reader, /* Parent class */
parse /* Name of function in C++ (must match Python name) */
/* Argument(s) */
);
}
double getLayerThickness() const override {
PYBIND11_OVERRIDE_PURE(
double, /* Return type */
Reader, /* Parent class */
getLayerThickness /* Name of function in C++ (must match Python name) */
/* Argument(s) */
);
}
};
class PyWriter : public slm::base::Writer {
public:
/* Inherit the constructors */
using slm::base::Writer::Writer;
/* Trampoline (need one for each virtual function) */
void write(const Header &header,
const std::vector<Model::Ptr> &models,
const std::vector<Layer::Ptr> &layers) override {
PYBIND11_OVERRIDE_PURE(
void, /* Return type */
Writer, /* Parent class */
write, /* Name of function in C++ (must match Python name) */
header, models, layers /* Argument(s) */
);
}
};
py::class_<slm::base::Reader, PyReader>(m, "Reader")
.def(py::init())
.def("setFilePath", &slm::base::Reader::setFilePath, py::arg("filename"))
.def("getFilePath", &slm::base::Reader::getFilePath)
.def("parse", &slm::base::Reader::parse)
.def("getFileSize", &slm::base::Reader::getFileSize)
.def("getLayerThickness", &slm::base::Reader::getLayerThickness)
.def("getModelById", &slm::base::Reader::getModelById, py::arg("mid"))
.def_property_readonly("layers", &slm::base::Reader::getLayers)
.def_property_readonly("models", &slm::base::Reader::getModels);
py::class_<slm::base::Writer, PyWriter>(m, "Writer")
.def(py::init())
.def(py::init<std::string>())
.def("setFilePath", &slm::base::Writer::setFilePath)
.def("getFilePath", &slm::base::Writer::getFilePath)
.def("getLayerMinMax", &slm::base::Writer::getLayerMinMax)
.def("getTotalNumHatches", &slm::base::Writer::getTotalNumHatches)
.def("getTotalNumContours", &slm::base::Writer::getTotalNumContours)
.def("getBoundingBox", &slm::base::Writer::getBoundingBox)
.def_property("sortLayers", &slm::base::Writer::isSortingLayers, &slm::base::Writer::setSortLayers)
.def("write", &slm::base::Writer::write, py::arg("header"), py::arg("models"), py::arg("layers"));
#endif
py::enum_<slm::LaserMode>(m, "LaserMode")
.value("Default", LaserMode::PULSE)
.value("CW", LaserMode::CW)
.value("Pulse", LaserMode::PULSE)
.export_values();
py::enum_<slm::ScanMode>(m, "ScanMode")
.value("Default", ScanMode::NONE)
.value("ContourFirst", ScanMode::CONTOUR_FIRST)
.value("HatchFirst", ScanMode::HATCH_FIRST)
.export_values();
py::class_<slm::LayerGeometry, std::shared_ptr<slm::LayerGeometry>> layerGeomPyType(m, "LayerGeometry", py::dynamic_attr());
layerGeomPyType.def(py::init())
.def_readwrite("bid", &LayerGeometry::bid)
.def_readwrite("mid", &LayerGeometry::mid)
.def_readwrite("coords", &LayerGeometry::coords)
.def_property("type", &LayerGeometry::getType, nullptr)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("bid"), self.attr("mid"), self.attr("coords"), self.attr("type"), self.attr("__dict__"));
}, [](const py::tuple &t) {
if (t.size() != 5)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<LayerGeometry>();
p->bid = t[0].cast<int>();
p->mid = t[1].cast<int>();
p->coords = t[2].cast<Eigen::MatrixXf>();
auto py_state = t[3].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::class_<slm::ContourGeometry, slm::LayerGeometry, std::shared_ptr<slm::ContourGeometry>>(m, "ContourGeometry", py::dynamic_attr())
.def(py::init())
.def(py::init<uint32_t, uint32_t>(), py::arg("mid"), py::arg("bid"))
.def_property("type", &ContourGeometry::getType, nullptr)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("bid"), self.attr("mid"), self.attr("coords"), self.attr("__dict__"));
}, [](const py::tuple &t) {
if (t.size() != 4)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<slm::ContourGeometry>();
p->bid = t[0].cast<int>();
p->mid = t[1].cast<int>();
p->coords = t[2].cast<Eigen::MatrixXf>();
auto py_state = t[3].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::class_<slm::HatchGeometry, slm::LayerGeometry, std::shared_ptr<HatchGeometry>>(m, "HatchGeometry", py::dynamic_attr())
.def(py::init())
.def(py::init<uint32_t, uint32_t>(), py::arg("mid"), py::arg("bid"))
.def_property("type", &HatchGeometry::getType, nullptr)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("bid"), self.attr("mid"), self.attr("coords"), self.attr("__dict__"));
}, [](const py::tuple &t) {
if (t.size() != 4)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<slm::HatchGeometry>();
p->bid = t[0].cast<int>();
p->mid = t[1].cast<int>();
p->coords = t[2].cast<Eigen::MatrixXf>();
auto py_state = t[3].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::class_<slm::PntsGeometry, slm::LayerGeometry, std::shared_ptr<slm::PntsGeometry>>(m, "PointsGeometry", py::dynamic_attr())
.def(py::init())
.def(py::init<uint32_t, uint32_t>(), py::arg("mid"), py::arg("bid"))
.def_property("type", &PntsGeometry::getType, nullptr)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("bid"), self.attr("mid"), self.attr("coords"), self.attr("__dict__"));
}, [](const py::tuple &t) {
if (t.size() != 4)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<slm::PntsGeometry>();
p->bid = t[0].cast<int>();
p->mid = t[1].cast<int>();
p->coords = t[2].cast<Eigen::MatrixXf>();
auto py_state = t[3].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::enum_<slm::LayerGeometry::TYPE>(layerGeomPyType, "LayerGeometryType")
.value("Invalid", slm::LayerGeometry::TYPE::INVALID)
.value("Pnts", slm::LayerGeometry::TYPE::PNTS)
.value("Polygon", slm::LayerGeometry::TYPE::POLYGON)
.value("Hatch", slm::LayerGeometry::TYPE::HATCH)
.export_values();
slm::bind_my_vector<std::vector<slm::BuildStyle::Ptr>>(m, "VectorBuildStyle");
slm::bind_my_vector<std::vector<slm::LayerGeometry::Ptr>>(m, "VectorLayerGeometry");
py::implicitly_convertible<py::list, std::vector<slm::BuildStyle::Ptr>>();
py::implicitly_convertible<py::list, std::vector<slm::LayerGeometry::Ptr>>();
#if 0
py::class_<std::vector<slm::LayerGeometry::Ptr> >(m, "LayerGeometryVector")
.def(py::init<>())
.def("clear", &std::vector<LayerGeometry::Ptr>::clear)
//.def("append",[](std::vector<LayerGeometry::Ptr> &v, LayerGeometry::Ptr &value) { v.push_back(value); },
// py::keep_alive<2,1>())
.def("append", (void (LayerGeomList::*)(const slm::LayerGeometry::Ptr &)) &LayerGeomList::push_back, py::keep_alive<1, 2>())
//.def("append", (void (std::vector<slm::LayerGeometry::Ptr>::*push_back)(const std::vector<slm::LayerGeometry::Ptr> &)(&std::vector<LayerGeometry::Ptr>::push_back))
.def("pop_back", &std::vector<LayerGeometry::Ptr>::pop_back)
.def("__len__", [](const std::vector<LayerGeometry::Ptr> &v) { return v.size(); })
.def("__iter__", [](std::vector<LayerGeometry::Ptr> &v) {
return py::make_iterator(v.begin(), v.end());
}, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
.def("__bool__", &std::vector<LayerGeometry::Ptr>::empty)
.def("__contains__",
[](const std::vector<LayerGeometry::Ptr> &v, const LayerGeometry::Ptr &x) {
return std::find(v.begin(), v.end(), x) != v.end();
},
py::arg("x"),
"Return true the container contains ``x``"
);
#endif
py::class_<slm::Header>(m, "Header", py::dynamic_attr())
.def(py::init())
.def_readwrite("filename", &Header::fileName)
.def_readwrite("creator", &Header::creator)
.def_property("version", &Header::version, &Header::setVersion)
.def_readwrite("zUnit", &Header::zUnit)
.def(py::pickle(
[](py::object self) { // __getstate__
return py::make_tuple(self.attr("filename"), self.attr("version"), self.attr("zUnit"), self.attr("__dict__"));
},
[](const py::tuple &t) {
if (t.size() != 4)
throw std::runtime_error("Invalid state!");
auto p = slm::Header();
p.fileName = t[0].cast<std::string>();
py::tuple version = t[1].cast<py::tuple>();
p.vMajor = version[0].cast<int>();
p.vMinor = version[1].cast<int>();
p.zUnit = t[2].cast<int>();
return p;
}
));
py::class_<slm::BuildStyle, std::shared_ptr<slm::BuildStyle>>(m, "BuildStyle", py::dynamic_attr())
.def(py::init())
.def_readwrite("bid", &BuildStyle::id)
.def_readwrite("name", &BuildStyle::name)
.def_readwrite("description", &BuildStyle::description)
.def_readwrite("laserPower", &BuildStyle::laserPower)
.def_readwrite("laserSpeed", &BuildStyle::laserSpeed)
.def_readwrite("laserFocus", &BuildStyle::laserFocus)
.def_readwrite("pointDistance", &BuildStyle::pointDistance)
.def_readwrite("pointExposureTime", &BuildStyle::pointExposureTime)
.def_readwrite("laserId", &BuildStyle::laserId)
.def_readwrite("laserMode", &BuildStyle::laserMode)
.def_readwrite("pointDelay", &BuildStyle::pointDelay)
.def_readwrite("jumpDelay", &BuildStyle::jumpDelay)
.def_readwrite("jumpSpeed", &BuildStyle::jumpSpeed)
.def("setStyle", &BuildStyle::setStyle, "Sets the paramters of the buildstyle",
py::arg("bid"),
py::arg("focus"),
py::arg("power"),
py::arg("pointExposureTime"),
py::arg("pointExposureDistance"),
py::arg("speed") = 0.0,
py::arg("laserId") = 1,
py::arg("laserMode") = slm::LaserMode::PULSE)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("bid"),
self.attr("laserPower"), self.attr("laserSpeed"), self.attr("laserFocus"),
self.attr("pointDistance"), self.attr("pointExposureTime"),
self.attr("laserId"), self.attr("laserMode"),
self.attr("name"), self.attr("description"),
self.attr("pointDelay"),
self.attr("jumpDelay"), self.attr("jumpSpeed"),
self.attr("description"),
self.attr("__dict__"));
},
[](const py::tuple &t) {
if (t.size() != 7)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<BuildStyle>();
p->id = t[0].cast<int>();
p->laserPower = t[1].cast<float>();
p->laserSpeed = t[2].cast<float>();
p->laserFocus = t[3].cast<float>();
p->pointDistance = t[4].cast<int>();
p->pointExposureTime = t[5].cast<int>();
p->laserId = t[6].cast<int>();
p->laserMode = t[7].cast<slm::LaserMode>();
p->name = t[8].cast<std::u16string>();
p->description = t[9].cast<std::u16string>();
p->pointDelay = t[10].cast<int>();
p->jumpDelay = t[11].cast<int>();
p->jumpSpeed = t[12].cast<int>();
p->description = t[13].cast<std::u16string>();
auto py_state = t[14].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::class_<slm::Model, std::shared_ptr<slm::Model>>(m, "Model", py::dynamic_attr())
.def(py::init())
.def(py::init<uint64_t, uint64_t>(), py::arg("mid"), py::arg("topSliceNum"))
.def_property("mid", &Model::getId, &Model::setId)
.def("__len__", [](const Model &s ) { return s.getBuildStyles().size(); })
.def_property("buildStyles",py::cpp_function(&slm::Model::buildStylesRef,py::return_value_policy::reference, py::keep_alive<1,0>()),
py::cpp_function(&slm::Model::setBuildStyles, py::keep_alive<1, 2>()))
//.def_property("buildStyles", &Model::getBuildStyles, &Model::setBuildStyles)
.def_property("topLayerId", &Model::getTopSlice, &Model::setTopSlice)
.def_property("name", &Model::getName, &Model::setName)
.def_property("buildStyleName", &Model::getBuildStyleName, &Model::setBuildStlyeName)
.def_property("buildStyleDescription", &Model::getBuildStyleDescription, &Model::setBuildStlyeDescription)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("mid"),
self.attr("name"),
self.attr("buildStyleName"),
self.attr("buildStyleDescription"),
self.attr("topLayerId"),
self.attr("buildStyles"),
self.attr("__dict__"));
},
[](const py::tuple &t) {
if (t.size() != 5)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<Model>(t[0].cast<int>(), /* Mid */
t[4].cast<int>() /* Top Layer Id */);
p->setName(t[1].cast<std::u16string>());
p->setBuildStlyeName(t[2].cast<std::u16string>());
p->setBuildStlyeDescription(t[3].cast<std::u16string>());
p->setBuildStyles(t[5].cast<std::vector<BuildStyle::Ptr>>());
auto py_state = t[6].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
py::class_<slm::Layer, std::shared_ptr<slm::Layer>>(m, "Layer", py::dynamic_attr())
.def(py::init())
.def(py::init<uint64_t, uint64_t>(), py::arg("id"), py::arg("z"))
.def("__len__", [](const Layer &s ) { return s.geometry().size(); })
.def_property_readonly("layerFilePosition", &Layer::layerFilePosition)
.def("isLoaded", &Layer::isLoaded)
.def("getPointsGeometry", &Layer::getPntsGeometry)
.def("getHatchGeometry", &Layer::getHatchGeometry)
.def("getContourGeometry", &Layer::getContourGeometry)
.def("appendGeometry", &Layer::appendGeometry, py::keep_alive<1, 2>())
// .def("geom", [](Layer &v) { return &(v.geometry()); }, py::keep_alive<1,0>())
.def_property("geometry",py::cpp_function(&Layer::geometryRef,py::return_value_policy::reference, py::keep_alive<1,0>()),
py::cpp_function(&Layer::setGeometry, py::keep_alive<1, 2>()))
.def_property("z", &Layer::getZ, &Layer::setZ)
.def_property("layerId", &Layer::getLayerId, &Layer::setLayerId)
.def("getGeometry", &Layer::getGeometry, py::arg("scanMode") = slm::ScanMode::NONE)
.def(py::pickle(
[](py::object self) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
return py::make_tuple(self.attr("layerId"), self.attr("z"), self.attr("geometry"), self.attr("__dict__"));
},
[](const py::tuple &t) {
if (t.size() != 4)
throw std::runtime_error("Invalid state!");
auto p = std::make_shared<Layer>(t[0].cast<int>(), /* Layer Id */
t[1].cast<int>() /* Layer Z */);
p->setGeometry(t[2].cast<std::vector<LayerGeometry::Ptr>>());
auto py_state = t[3].cast<py::dict>();
return std::make_pair(p, py_state);
}
));
#ifdef PROJECT_VERSION
m.attr("__version__") = "PROJECT_VERSION";
#else
m.attr("__version__") = "dev";
#endif
}
| 20,203
|
C++
|
.cpp
| 365
| 40.487671
| 173
| 0.510012
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,835
|
Slm.cpp
|
drlukeparry_libSLM/App/Slm.cpp
|
#include <math.h>
#include <float.h>
#include <QPointF>
#include <QPair>
#include <QDebug>
#ifndef QT_NO_CONCURRENT
#include <QtConcurrent/QtConcurrentMap>
#endif
#include "Layer.h"
#include "Model.h"
#include "Slm.h"
namespace slm {
// Multithreaded operation for generting the layer index
struct GenLayerIndex
{
GenLayerIndex(Slm *slm) : _slm(slm) { this->_scanMode = this->_slm->getScanMode(); }
typedef QPair<qint64, Slm::node> result_type;
QPair<qint64, Slm::node> operator()(const Layer::Ptr &layer) const
{
QList<LayerGeometry *> lgeoms = layer->getGeometry(this->_scanMode);
Slm::node layerNode;
double layerTime = 0.f;
int j = 0;
for(QList<LayerGeometry *>::const_iterator lgeom = lgeoms.begin(); lgeom != lgeoms.end(); ++lgeom, j++) {
double geomTime = this->_slm->calcGeomTime(*lgeom);
layerNode.addChild(j, geomTime);
layerTime += geomTime; // Add to the overall layer time
}
layerNode.setNodeValue(layerTime);
return QPair<qint64, Slm::node>(layer->getLayerId(), layerNode);
}
private:
Slm *_slm;
slm::ScanMode _scanMode;
};
} // end of Namespace
using namespace slm;
Slm::Slm() : layerThickness(0.),
scanmode(HATCH_FIRST),
layerAdditionTime(0.),
layerCoolingTime(0.)
{
}
Slm::~Slm()
{
}
void Slm::invalidateCache()
{
_cache.clear();
}
void Slm::clear()
{
layers.clear();
models.clear();
tindex.clear(); // Clear the Time Index tree
}
void Slm::parseGeometry()
{
this->createLayerIndex();
}
void Slm::setBuild(const std::vector<Layer::Ptr> &layers,
const std::vector<Model::Ptr> &models,
ScanMode mode,
const double lThickness,
const double lAdditionTime,
const double lCoolingTime)
{
this->clear();
this->layerThickness = lThickness;
this->scanmode = mode;
this->layers = layers; // Make a copy of vector but not a deep copy;
this->models = models;
this->layerAdditionTime = lAdditionTime;
this->layerCoolingTime = lCoolingTime;
this->parseGeometry();
}
Model::Ptr Slm::getModelById(uint mid) const
{
// Iterate through all buildStyle elements and check if matching id;
// Return true if found
QList<Model *>::const_iterator it = this->models.begin();
for(; it != this->models.end(); ++it ) {
if((*it)->getId() == mid) {
return *it;
}
}
return 0;
}
void Slm::createLayerIndex()
{
// Clear the time tree index
this->tindex.clear();
#ifndef QT_NO_CONCURRENT
typedef QPair<qint64, Slm::node> NodePair ;
// Multithreaded option for generating layer indexes
QList<NodePair> layerNodes = QtConcurrent::blockingMapped(layers, GenLayerIndex(this));
// Add the pairs to the root tree
for(QList<NodePair>::const_iterator it = layerNodes.cbegin(); it != layerNodes.cend(); ++it) {
this->tindex.addChild((*it).first, (*it).second);
}
#else
int i = 0;
for(QList<Layer::Ptr>::const_iterator it = layers.cbegin(); it != layers.cend(); ++it, i++) {
QList<LayerGeometry *> lgeoms = (*it)->getGeometry(scanmode);
node layerNode;
double layerTime = 0.f;
int j = 0;
for(QList<LayerGeometry *>::const_iterator lgeom = lgeoms.begin(); lgeom != lgeoms.end(); ++lgeom, j++) {
double geomTime = this->calcGeomTime(*lgeom);
//qDebug() << "Adding node" << i << "," << j << "(" << geomTime << ")";
layerNode.addChild(j, geomTime);
layerTime += geomTime; // Add to the overall layer time
}
layerNode.setNodeValue(layerTime);
this->tindex.addChild(i, layerNode);
}
#endif
}
bool Slm::isLaserOnByTime(const double t) const
{
bool isLaserOn = false;
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
QPointF laserPos;
double buildTime = 0.0 - this->getLayerAdditionTime();
int i = 0;
for(; it != this->tindex.end(); ++it, i++) {
node layerNode = it.value();
double layerTime = layerNode.getNodeValue();
buildTime += this->getLayerAdditionTime();
if (this->isBoundByTimeInterval(t,buildTime, layerTime)) {
// In Layer Geometry Section
isLaserOn = true;
break;
}
buildTime += layerTime + this->getLayerCoolingTime();
}
}
return isLaserOn;
}
double Slm::calcGeomTime(LayerGeometry *lgeom) const
{
Model *model = this->getModelById(lgeom->mid);
BuildStyle *bstyle = model->getBuildStyleById(lgeom->bid);
float laserSpeed = bstyle->laserSpeed;
double pathLen = 0.f;
if(lgeom->getType() == LayerGeometry::HATCH) {
for(int i = 0; i < lgeom->coords.length() / 2; i++) {
QPointF v = lgeom->coords.at(2*i+1) - lgeom->coords.at(2*i); // Vector between line segment
const double &x = v.rx();
const double &y = v.rx();
pathLen += sqrt(x*x + y*y);
}
} else if(lgeom->getType() == LayerGeometry::POLYGON) {
for(int i = 0; i < lgeom->coords.length() -1; i++) {
QPointF v = lgeom->coords.at(i+1) - lgeom->coords.at(i); // Vector between line segment
const double &x = v.rx();
const double &y = v.rx();
pathLen += sqrt(x*x + y*y);
}
} else {
return 0.f;
}
// Return the time on this path
return pathLen / laserSpeed;
}
void Slm::getPointsInGeom(const double &offset, LayerGeometry *lgeom, QPointF &pnt1, QPointF &pnt2) const
{
Model *model = this->getModelById(lgeom->mid);
BuildStyle *bstyle = model->getBuildStyleById(lgeom->bid);
double distTravelled = bstyle->laserSpeed * offset; // Distance covered for offset of this geometry
if(lgeom->getType() == LayerGeometry::HATCH) {
double pathPos = 0.f;
for(int i = 0; i < lgeom->coords.length() / 2; ++i) {
const QPointF &p1 = lgeom->coords.at(2*i);
const QPointF &p2 = lgeom->coords.at(2*i+i);
QPointF v = p2 - p1; // Vector between line segmen
pathPos += sqrt(pow(v.x(), 2) + pow(v.y(), 2));
if(distTravelled < pathPos) {
pnt2 = p2;
pnt1 = p1;
return;
}
}
} else if(lgeom->getType() == LayerGeometry::POLYGON) {
ContourGeometry *geom = static_cast<ContourGeometry *>(lgeom);
double pathPos = 0.f;
for(int i = 0; i < geom->coords.length() -1; ++i) {
const QPointF &p1 = geom->coords.at(i);
const QPointF &p2 = geom->coords.at(i+1);
QPointF v = p2 - p1; // Vector between line segmen
pathPos += sqrt(pow(v.x(), 2) + pow(v.y(), 2));
if(distTravelled < pathPos) {
pnt2 = p2;
pnt1 = p1;
return;
}
}
}
}
QPointF Slm::getPointInGeom(const double &offset, LayerGeometry *lgeom) const
{
Model *model = this->getModelById(lgeom->mid);
BuildStyle *bstyle = model->getBuildStyleById(lgeom->bid);
double distTravelled = bstyle->laserSpeed * offset; // Distance covered for offset of this geometry
QPointF laserPos;
if(lgeom->getType() == LayerGeometry::HATCH) {
double pathPos = 0.f;
bool onContour = false;
QPointF v;
QPointF p1;
for(int i = 0; i < lgeom->coords.length() / 2; ++i) {
v = lgeom->coords.at(2*i+1) -lgeom->coords.at(2*i); // Vector between line segment
pathPos += sqrt(pow(v.x(), 2) + pow(v.y(), 2));
if(distTravelled < pathPos) {
onContour = true;
// Save p1 for later
p1 = lgeom->coords.at(2*i);
break;
}
}
if(onContour) {
double len = sqrt(pow(v.x(), 2) + pow(v.y(), 2));
// Find the relative position on the line based on the delta
double relPos = (len - (pathPos - distTravelled)) / len;
laserPos = p1 + v * relPos;
} else {
return QPointF(); // TODO Throw an exception
}
} else if(lgeom->getType() == LayerGeometry::POLYGON) {
ContourGeometry *geom = static_cast<ContourGeometry *>(lgeom);
double pathPos = 0.f;
bool onContour = false;
QPointF v;
QPointF p1;
for(int i = 0; i < geom->coords.length() -1; ++i) {
v = geom->coords.at(i+1) - geom->coords.at(i); // Vector between line segment
pathPos += sqrt(pow(v.x(), 2) + pow(v.y(), 2));
if(distTravelled < pathPos) {
// Save p1 for later
p1 = geom->coords.at(i);
onContour = true;
break;
}
}
if(onContour) {
double len = sqrt(pow(v.x(), 2) + pow(v.y(), 2));
// Find the relative position on the line based on the delta
double relPos = (len - (pathPos - distTravelled)) / len;
laserPos = p1 + v * relPos;
} else {
return QPointF(0.,0.);
}
}
return laserPos;
}
int Slm::getLayerIdByTime(const double &t) const
{
// It is assumed the first layer always starts from time zero
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double layerTimePos = 0.f;
for(int i =0; it != this->tindex.end(); ++it, i++) {
node layerNode = (*it);
layerTimePos += layerNode.getNodeValue() + this->getLayerCoolingTime();
if(t < layerTimePos) {
return i;
}
layerTimePos += this->getLayerAdditionTime(); // The layer is added after the laser scan for the next layer
}
// Failed to find the layer by time
return -1;
}
}
double Slm::getTimeByLayerId(const int layerId) const
{
Q_ASSERT(layerId >= this->layers.length());
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double layerTimePos = 0.f;
int i = layerId;
// Use reverse delta loop to count first level of time index tree
while(i--) {
const node layerNode = (it++).value();
layerTimePos += this->getLayerAdditionTime() + layerNode.getNodeValue() + this->getLayerCoolingTime();
}
return layerTimePos;
}
}
double Slm::getTimeByLayerGeomId(const int layerId, const int geomId) const
{
Q_ASSERT(layerId >= this->layers.length());
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double layerTimePos = 0.f;
int i = layerId;
// Use reverse delta loop to count first level of time index tree
node layerNode = it.value();
while(i--) {
layerNode = (it++).value();
layerTimePos += this->getLayerAdditionTime() + layerNode.getNodeValue() + this->getLayerCoolingTime();
}
node::const_iterator git = layerNode.getChildren().begin();
int j = geomId;
while(j--) {
node geomNode = (git++).value();
layerTimePos += geomNode.getNodeValue();
}
return layerTimePos;
}
}
LayerGeometry * Slm::getLayerGeometryByTime(const double t) const
{
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double buildTime = -this->getLayerAdditionTime();
for(int i = 0; it != this->tindex.end(); ++it, i++) {
const node layerNode = it.value();
const double layerTime = layerNode.getNodeValue();
buildTime += this->getLayerAdditionTime();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + layerTime - FLT_EPSILON) {
node::const_iterator lgeom = layerNode.begin();
for(int j = 0; lgeom != layerNode.end(); ++lgeom, j++) {
const node layerGeomNode = lgeom.value();
double lGeomTime = layerGeomNode.getNodeValue();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + lGeomTime - FLT_EPSILON) {
// Access the layer using index i
Layer::Ptr layer = layers.at(i);
return layer->getGeometry(scanmode).at(j);
}
}
// TODO throw an exception since the layer geom at this time was not found
return 0;
}
buildTime += layerTime + this->getLayerCoolingTime(); // Add the layer time if the time is not in this layer
}
} else {
return 0;
}
}
void Slm::getLaserParameters(const double &t, float &power, int &expTime, int &pntDist, bool &isLaserOn) const
{
// Set laser default to off
isLaserOn = false;
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double buildTime = 0.0 - this->getLayerAdditionTime();
int i = 0;
for(; it != this->tindex.end(); ++it, i++) {
node layerNode = it.value();
double layerTime = layerNode.getNodeValue();
if( this->isBoundByTimeInterval(t,buildTime,this->getLayerAdditionTime()) ) {
return;
}
buildTime += this->getLayerAdditionTime();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + layerTime - FLT_EPSILON) {
int j = 0;
node::const_iterator lgeom = layerNode.begin();
for(; lgeom != layerNode.end(); ++lgeom, j++) {
node layerGeomNode = lgeom.value();
double lGeomTime = layerGeomNode.getNodeValue();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + lGeomTime - FLT_EPSILON) {
// Access the layer using index i
Layer::Ptr layer = layers.at(i);
LayerGeometry *lgeom = layer->getGeometry(scanmode).at(j);
Model *model = this->getModelById(lgeom->mid);
BuildStyle *bstyle = model->getBuildStyleById(lgeom->bid);
power = bstyle->laserPower;
pntDist = bstyle->pointDistance;
expTime = bstyle->pointExposureTime;
isLaserOn = true;
return;
}
buildTime += lGeomTime;
}
// TODO throw an exception
return;
}
if(this->isBoundByTimeInterval(t, buildTime, this->getLayerAdditionTime())) {
return;
}
buildTime += layerTime + this->getLayerCoolingTime();
}
} else {
}
}
void Slm::getLaserVelocity(const double &t, double &dx, double &dy, bool &isLaserOn) const
{
isLaserOn = false;
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double buildTime = -this->getLayerAdditionTime();
int i = 0;
for(; it != this->tindex.end(); ++it, i++) {
node layerNode = it.value();
double layerTime = layerNode.getNodeValue();
buildTime += this->getLayerAdditionTime();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + layerTime - FLT_EPSILON) {
int j = 0;
node::const_iterator lgeom = layerNode.begin();
for(; lgeom != layerNode.end(); ++lgeom, j++) {
node layerGeomNode = lgeom.value();
double lGeomTime = layerGeomNode.getNodeValue();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + lGeomTime - FLT_EPSILON) {
Layer::Ptr layer = layers.at(i);
LayerGeometry *lgeom = layer->getGeometry(scanmode).at(j);
Model *model = this->getModelById(lgeom->mid);
BuildStyle *bstyle = model->getBuildStyleById(lgeom->bid);
QPointF p1, p2, v;
this->getPointsInGeom(t-buildTime, lgeom, p1, p2);
double length = sqrt( pow(p2.rx() - p1.rx(),2) + pow(p2.ry() - p1.ry(), 2) );
v = (p2 - p1) / length; // Normalize the point path
v *= bstyle->laserSpeed;
dx = v.x();
dy = v.y();
isLaserOn = true;
return;
}
}
// TODO throw an exception
return;
}
}
}
}
void Slm::getLaserPosition(const double &t, double &x, double &y, double &z, bool &isLaserOn) const
{
isLaserOn = false;
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
QPointF laserPos;
double buildTime = -this->getLayerAdditionTime();
int i = 0;
for(; it != this->tindex.end(); ++it, i++) {
node layerNode = it.value();
double layerTime = layerNode.getNodeValue();
buildTime += this->getLayerAdditionTime();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + layerTime - FLT_EPSILON) {
int j = 0;
node::const_iterator lgeom = layerNode.begin();
for(; lgeom != layerNode.end(); ++lgeom, j++) {
node layerGeomNode = lgeom.value();
double lGeomTime = layerGeomNode.getNodeValue();
if(t > buildTime - FLT_EPSILON &&
t < buildTime + lGeomTime - FLT_EPSILON) {
// Access the layer using index i
Layer::Ptr layer = layers.at(i);
LayerGeometry *lgeom = layer->getGeometry(scanmode).at(j);
laserPos = this->getPointInGeom(t-buildTime, lgeom);
x = laserPos.x();
y = laserPos.y();
z = this->layerThickness *i;
isLaserOn = true;
return;
}
buildTime += lGeomTime;
}
break;
}
buildTime += layerTime + this->getLayerCoolingTime();
}
} else {
}
}
double Slm::getBuildTime() const
{
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double buildTime = 0;
for(; it != this->tindex.end(); ++it) {
node layerNode = it.value();
buildTime += this->getLayerAdditionTime() + layerNode.getNodeValue() + this->getLayerCoolingTime();
}
buildTime -= this->getLayerAdditionTime(); // First layer doesn't include addition time
return buildTime;
} else {
return -1;
}
}
double Slm::getBuildEnergy() const
{
if(!this->tindex.empty()) {
node::const_iterator it = this->tindex.begin();
double buildTime = 0;
for(; it != this->tindex.end(); ++it) {
// buildTime += (float) (*it).value;
}
return buildTime;
} else {
return -1;
}
}
| 19,698
|
C++
|
.cpp
| 499
| 28.945892
| 120
| 0.543501
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,836
|
Reader.cpp
|
drlukeparry_libSLM/App/Reader.cpp
|
#include <algorithm>
#include <iostream>
#include <fstream>
#include <filesystem/fwd.h>
#include <filesystem/resolver.h>
#include <filesystem/path.h>
#include "Layer.h"
#include "Model.h"
#include "Reader.h"
using namespace slm;
using namespace base;
namespace fs = filesystem;
Reader::Reader(const std::string &fileLoc) : ready(false)
{
setFilePath(fileLoc);
}
Reader::Reader() : ready(false)
{
}
Reader::~Reader()
{
models.clear();
layers.clear();
}
int64_t Reader::getFileSize() const
{
if(!this->isReady()) {
return -1;
}
fs::path checkPath(this->filePath);
return checkPath.file_size();
//const auto begin = myfile.tellg();
//testFile.seekg (0, ios::end);
//const auto end = testFile.tellg();
//const auto fsize = (end-begin);
}
void Reader::setFilePath(std::string path)
{
fs::path checkPath(path);
if (!(checkPath.exists() &&
checkPath.is_file()) ) {
std::cerr << "File '" << checkPath.str() << "' does not exist." << std::endl;
this->setReady(false);
} else {
this->setReady(true);
std::cout << "File '" << checkPath.str() << "' is ready to read" << std::endl;
this->filePath = path;
}
}
Model::Ptr Reader::getModelById(uint64_t mid) const
{
// Iterate through all buildStyle elements and check if matching id;
// Return true if found
auto result = std::find_if(models.cbegin(), models.cend(),
[&mid](Model::Ptr it){return it->getId() == mid;});
return (result != models.cend()) ? *result : Model::Ptr();
}
Layer::Ptr Reader::getTopLayerByPosition(const std::vector<Layer::Ptr> &layers)
{
uint64_t zMax = 0;
Layer::Ptr fndLayer;
for(auto layer : layers) {
if(layer->getZ() > zMax) {
fndLayer = layer;
zMax = layer->getZ();
}
}
return fndLayer;
}
Layer::Ptr Reader::getTopLayerById(const std::vector<Layer::Ptr> &layers)
{
uint64_t zId = 0;
Layer::Ptr fndLayer;
for(auto layer : layers) {
if(layer->getLayerId() > zId) {
fndLayer = layer;
zId = layer->getLayerId();
}
}
return fndLayer;
}
int Reader::parse()
{
if(!this->isReady()) {
std::cerr << "File is not ready for parsing";
return -1;
}
std::ifstream file;
file.open(this->filePath, std::ifstream::binary);
if(!file.is_open()) {
std::cerr << "File '" << filePath << "' could not be open for reading";
return -1;
}
file.close();
return 1;
}
| 2,592
|
C++
|
.cpp
| 96
| 21.947917
| 86
| 0.604642
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,837
|
Writer.cpp
|
drlukeparry_libSLM/App/Writer.cpp
|
#include <iostream>
#include <fstream>
#include <filesystem/fwd.h>
#include <filesystem/resolver.h>
#include <filesystem/path.h>
#include "Writer.h"
namespace fs = filesystem;
using namespace slm;
using namespace base;
Writer::Writer(const char * fname) : ready(false),
mSortLayers(false)
{
this->setFilePath(std::string(fname));
}
Writer::Writer(const std::string &fname) : ready(false),
mSortLayers(false)
{
this->setFilePath(fname);
}
Writer::Writer() : ready(false)
{
}
Writer::~Writer()
{
}
void Writer::getFileHandle(std::fstream &file) const
{
if(this->isReady()) {
file.open(filePath,std::fstream::in | std::fstream::out | std::fstream::trunc | std::fstream::binary);
if(!file.is_open()) {
std::cerr << "Cannot create file handler - " << filePath << std::endl;
}
}
}
void Writer::setFilePath(const std::string &path)
{
this->setReady(true);
this->filePath = path;
std::cout << "File '" << path << "' is ready to write" << std::endl;
}
Layer::Ptr Writer::getTopLayerByPosition(const std::vector<Layer::Ptr> &layers)
{
uint64_t zMax = 0;
Layer::Ptr fndLayer;
for(auto layer : layers) {
if(layer->getZ() > zMax) {
fndLayer = layer;
zMax = layer->getZ();
}
}
return fndLayer;
}
Layer::Ptr Writer::getTopLayerById(const std::vector<Layer::Ptr> &layers)
{
uint64_t zId = 0;
Layer::Ptr fndLayer;
for(auto layer : layers) {
if(layer->getLayerId() > zId) {
fndLayer = layer;
zId = layer->getLayerId();
}
}
return fndLayer;
}
std::vector<Layer::Ptr> Writer::sortLayers(const std::vector<Layer::Ptr> &layers)
{
std::vector<Layer::Ptr> layersCpy(layers);
std::sort(layersCpy.begin(), layersCpy.end(), [](Layer::Ptr a, Layer::Ptr b) {
return a->getZ() < b->getZ();
});
return layersCpy;
}
int64_t Writer::getTotalNumHatches(const std::vector<Layer::Ptr> &layers)
{
return Writer::getTotalGeoms<HatchGeometry>(layers);
}
int64_t Writer::getTotalNumContours(const std::vector<Layer::Ptr> &layers)
{
return Writer::getTotalGeoms<ContourGeometry>(layers);
}
void Writer::getLayerBoundingBox(float *bbox, Layer::Ptr layer)
{
float minX = 1e9, minY = 1e9 , maxX = -1e9, maxY = -1e9;
for(auto geom : layer->geometry()) {
auto minCols = geom->coords.colwise().minCoeff();
auto maxCols = geom->coords.colwise().maxCoeff();
if(minCols[0, 0] < minX)
minX = minCols[0,0];
if(minCols[0,1] < minY)
minY = minCols[0,1];
if(maxCols[0,0] > maxX)
maxX = maxCols[0,0];
if(maxCols[0,1] > maxY)
maxY = maxCols[0,1];
}
}
void Writer::getBoundingBox(float *bbox, const std::vector<Layer::Ptr> &layers)
{
float minX = 1e9, minY = 1e9 , maxX = -1e9, maxY = -1e9;
for (auto layer: layers) {
for(auto geom : layer->geometry()) {
auto minCols = geom->coords.colwise().minCoeff();
auto maxCols = geom->coords.colwise().maxCoeff();
if(minCols[0, 0] < minX)
minX = minCols[0,0];
if(minCols[0,1] < minY)
minY = minCols[0,1];
if(maxCols[0,0] > maxX)
maxX = maxCols[0,0];
if(maxCols[0,1] > maxY)
maxY = maxCols[0,1];
}
}
bbox[0] = minX;
bbox[1] = maxX;
bbox[2] = minY;
bbox[3] = maxY;
}
std::tuple<float, float> Writer::getLayerMinMax(const std::vector<slm::Layer::Ptr> &layers)
{
float zMin = 0.0;
float zMax = 0.0;
float zPos = 0.0;
for (auto layer : layers) {
zPos = layer->getZ();
if(zPos < zMin)
zMin = zPos;
if(zPos > zMax)
zMax = zPos;
}
return std::make_tuple(zMin, zMax);
}
| 3,947
|
C++
|
.cpp
| 132
| 23.575758
| 110
| 0.585722
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,838
|
Iterator.cpp
|
drlukeparry_libSLM/App/Iterator.cpp
|
#include <assert.h>
#include <Base/Tree.h>
#include "Layer.h"
#include "Model.h"
#include "Slm.h"
#include "Iterator.h"
using namespace slm;
Iterator::Iterator(Slm *val) : _inc(0),
_layerInc(0),
_layerGeomInc(0),
obj(val)
{
this->_endTime = this->obj->getBuildTime();
}
Iterator::~Iterator()
{
}
// Define prefix increment operator.
Iterator& Iterator::operator++()
{
this->next();
return *this;
}
// Define postfix increment operator.
Iterator Iterator::operator++(int)
{
Iterator temp = *this;
++*this;
return temp;
}
int Iterator::getCurrentLayerNumber() const
{
return this->_layerInc;
}
Layer::Ptr Iterator::getCurrentLayer() const
{
assert(this->_layerInc < this->obj->layers.length());
return this->obj->layers.at(this->_layerInc);
}
void Iterator::seek(const double &time)
{
this->_inc = time;
this->_layerInc = this->obj->getLayerIdByTime(time);
}
void Iterator::seekLayer(const int &layerNum)
{
this->_inc = this->obj->getTimeByLayerId(layerNum);
this->_layerInc = layerNum;
}
bool Iterator::more() const
{
return this->_inc + this->_timeInc < this->_endTime;
}
State Iterator::value() const
{
if(this->_inc > this->_endTime) {
State state;
return state;
}
State state;
state.time = this->_inc;
state.layer = this->_layerInc;
double z;
this->obj->getLaserPosition(this->_inc,
state.position.rx(),
state.position.ry(),
z,
state.laserOn);
this->obj->getLaserVelocity(this->_inc,
state.velocity.rx(),
state.velocity.ry(),
state.laserOn);
this->obj->getLaserParameters(this->_inc,
state.power,
state.pntExposureTime,
state.pntDistance,
state.laserOn);
return state;
}
void Iterator::next()
{
if(this->_inc > this->_endTime)
this->_inc = this->_endTime;
else
this->_inc += this->_timeInc;
}
LayerIterator::LayerIterator(Slm *val, int layerId) : Iterator(val)
{
this->_layerInc = layerId;
node n = this->obj->getTimeIndex().getValue(layerId);
this->_endTime = n.getNodeValue();
}
LayerIterator::~LayerIterator()
{
}
LayerGeomIterator::LayerGeomIterator(Slm *val) : Iterator(val)
{
this->_layerInc = 0;
this->_layerGeomInc = 0;
this->_layerCache = this->obj->getLayers();
this->_layerIt = this->_layerCache.cbegin();
this->_layerGeomCache = (*_layerIt)->getGeometry(this->obj->getScanMode());
this->_layerGeomIt = this->_layerGeomCache.cbegin();
}
LayerGeomIterator::~LayerGeomIterator()
{
}
// Define prefix increment operator.
LayerGeomIterator& LayerGeomIterator::operator++()
{
this->next();
return *this;
}
// Define postfix increment operator.
LayerGeomIterator LayerGeomIterator::operator++(int)
{
LayerGeomIterator temp = *this;
++*this;
return temp;
}
double LayerGeomIterator::getCurrentTime() const
{
return this->obj->getTimeByLayerGeomId(this->_layerInc, this->_layerGeomInc);
}
int LayerGeomIterator::getCurrentLayerNumber() const
{
return this->_layerInc;
}
Layer::Ptr LayerGeomIterator::getCurrentLayer() const
{
return *this->_layerIt;
}
void LayerGeomIterator::seek(const double &time)
{
this->_inc = time;
int layerNum = this->obj->getLayerIdByTime(time);
if(layerNum < 0) {
return; // Invalid time provided to seek too
}
LayerGeometry *lgeom = this->obj->getLayerGeometryByTime(time);
if(!lgeom){
return; // invalid time provided
}
this->seekLayer(layerNum);
this->_layerGeomCache = (*this->_layerIt)->getGeometry(this->obj->getScanMode());
this->_layerGeomIt = this->_layerGeomCache.cbegin();
bool found = false;
// Reverse foconstBeginr loop so iterator is at beginning of the layer
for(; this->_layerGeomIt != this->_layerGeomCache.begin(); this->_layerGeomIt++, this->_layerGeomInc) {
// Check if geom found matches rather than parsing the tree
if(*this->_layerGeomIt == lgeom) {
found = true;
break;
}
}
if(!found) {
qWarning() << "Layer Geometry not found during seek";
}
}
void LayerGeomIterator::seekLayer(const int &layerNum)
{
this->_layerIt = this->obj->getLayers().begin();
this->_layerIt += layerNum;
this->_layerInc = layerNum;
}
bool LayerGeomIterator::more() const
{
if(this->_layerIt +1 != this->_layerCache.constEnd()) {
return true; // More layers exist
} else if(this->_layerGeomIt + 1 != this->_layerGeomCache.constEnd()) {
return true; // More layer geoms exist on current layer
}
return false;
}
void LayerGeomIterator::next()
{
// Get the current layer
Layer::Ptr layer = *this->_layerIt;
this->_layerGeomInc++;
if(++(this->_layerGeomIt) == this->_layerGeomCache.constEnd()) {
this->_layerIt++; // Iterate to the next layer
this->_layerInc++;
this->_layerGeomCache.clear(); // Invalidate cache
}
// Check cache
if(_layerGeomCache.empty()) {
if(this->_layerIt != this->_layerCache.constEnd()) {
this->_layerGeomCache = (*_layerIt)->getGeometry(this->obj->getScanMode());
// Reset geometry iterators
this->_layerGeomIt = this->_layerGeomCache.constBegin();
this->_layerGeomInc = 0;
}
}
}
LayerGeometry * LayerGeomIterator::getLayerGeometry() const
{
return this->value();
}
LayerGeometry * LayerGeomIterator::value() const
{
return *this->_layerGeomIt;
}
LaserScanIterator::LaserScanIterator(Slm *val) : LayerGeomIterator(val)
{
this->_curLayerGeom = LayerGeomIterator::value();
this->_pntIt = this->_curLayerGeom->coords.cbegin();
}
LaserScanIterator::~LaserScanIterator()
{
}
bool LaserScanIterator::more() const
{
if(LayerGeomIterator::more()) {
return true;
} else {
if(this->_curLayerGeom->getType() == LayerGeometry::HATCH) {
return this->_pntIt + 2 != this->_curLayerGeom->coords.cend();
} else if(this->_curLayerGeom->getType() == LayerGeometry::POLYGON) {
return this->_pntIt + 1 != this->_curLayerGeom->coords.cend();
} else {
return this->_pntIt + 1 != this->_curLayerGeom->coords.cend();
}
}
}
LaserScan LaserScanIterator::value() const
{
LaserScan scan;
scan.type = this->_curLayerGeom->getType();
scan.layer = this->_layerInc;
scan.tStart = this->getCurrentTime();
scan.tEnd = this->getCurrentTime() + this->calcScanTime();
if(scan.type == LayerGeometry::HATCH) {
scan.start = *(this->_pntIt); // Return value
scan.end = *(this->_pntIt + 1);
} else if(scan.type == LayerGeometry::POLYGON) {
scan.start = *(this->_pntIt ); // Return value
scan.end = *(this->_pntIt+1);
} else {
scan.start = *(this->_pntIt); // Return value
scan.end = scan.start;
}
return scan;
}
// Define prefix increment operator.
LaserScanIterator& LaserScanIterator::operator++()
{
this->next();
return *this;
}
// Define postfix increment operator.
LaserScanIterator LaserScanIterator::operator++(int)
{
LaserScanIterator temp = *this;
++*this;
return temp;
}
double LaserScanIterator::getCurrentTime() const
{
return this->_layerGeomTime + this->_relTime;
}
// Calculates the current scan time of the iterator
double LaserScanIterator::calcScanTime() const
{
double scanTime;
// Get Laser Parameters
LayerGeometry *geom = this->getLayerGeometry();
Model *model = this->obj->getModelById(geom->mid);
BuildStyle *bstyle = model->getBuildStyleById(geom->bid);
switch(geom->getType()) {
case LayerGeometry::HATCH:
case LayerGeometry::POLYGON: {
QPointF start, end;
start = *(this->_pntIt); // Return value
end = *(this->_pntIt + 1);
QPointF delta = end-start;
double dist = sqrt(pow(delta.x(),2) + pow(delta.y(),2));
scanTime = dist / bstyle->laserSpeed;
} break;
default:
scanTime = bstyle->pointExposureTime; break;
}
return scanTime;
}
void LaserScanIterator::next()
{
bool newLayerGeom = false;
// Add on previous laser scan time
this->_relTime += this->calcScanTime();
if(this->_curLayerGeom->getType() == LayerGeometry::HATCH) {
this->_pntIt++; // Advance once since coords are in pairs
this->_pntIt++;
newLayerGeom = this->_pntIt == this->_curLayerGeom->coords.cend();
} else if(this->_curLayerGeom->getType() == LayerGeometry::POLYGON) {
this->_pntIt++;
newLayerGeom = this->_pntIt == this->_curLayerGeom->coords.cend() - 1;
} else {
this->_pntIt++;
newLayerGeom = this->_pntIt == this->_curLayerGeom->coords.cend();
}
if(newLayerGeom) {
// Clear the previous layerGeometry
if(LayerGeomIterator::more()) {
LayerGeomIterator::next(); // Iterate to the next LayerGeometry
this->_relTime = 0; // Reset relative time for current layer geometry
this->_curLayerGeom = LayerGeomIterator::value();
this->_pntIt = this->_curLayerGeom->coords.cbegin();
this->_layerGeomTime = LayerGeomIterator::getCurrentTime();
}
}
}
| 9,723
|
C++
|
.cpp
| 310
| 25.341935
| 107
| 0.622831
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,839
|
Layer.cpp
|
drlukeparry_libSLM/App/Layer.cpp
|
#include <cassert>
#include <algorithm>
#include <exception>
#include "Layer.h"
using namespace slm;
LayerGeometry::LayerGeometry() : mid(0),
bid(0)
{
}
LayerGeometry::LayerGeometry(uint32_t modelId, uint32_t buildStyleId ) : mid(modelId),
bid(buildStyleId)
{
}
LayerGeometry::~LayerGeometry()
{
}
Layer::Layer() : lid(0),
z(0),
mLayerPos(0),
mIsLoaded(false)
{
}
Layer::Layer(uint64_t id, uint64_t zVal) : lid(id),
z(zVal),
mLayerPos(0),
mIsLoaded(false)
{
}
Layer::~Layer()
{
mGeometry.clear();
}
void Layer::setLayerFilePosition(const uint64_t &position)
{
mLayerPos = position;
}
void Layer::setLayerId(const uint64_t &id)
{
lid = id;
}
void Layer::setZ(const uint64_t &val)
{
z = val;
}
void Layer::clear()
{
mGeometry.clear();
}
void Layer::setIsLoaded(const bool &isLoaded)
{
mIsLoaded = isLoaded;
}
void Layer::setGeometry(const std::vector<LayerGeometry::Ptr> &geoms) {
mGeometry = geoms;
}
void Layer::appendGeometry(LayerGeometry::Ptr geom)
{
if(!geom)
return;
mGeometry.push_back(geom);
}
int64_t Layer::addContourGeometry(LayerGeometry::Ptr geom)
{
if(!geom)
return -1;
assert(geom->getType() == LayerGeometry::POLYGON);
mGeometry.push_back(geom);
return mGeometry.size();
}
int64_t Layer::addHatchGeometry(LayerGeometry::Ptr geom)
{
if(!geom)
return -1;
assert(geom->getType() == LayerGeometry::HATCH);
mGeometry.push_back(geom);
return mGeometry.size();
}
int64_t Layer::addPntsGeometry(LayerGeometry::Ptr geom)
{
if(!geom)
return -1;
assert(geom->getType() == LayerGeometry::PNTS);
mGeometry.push_back(geom);
return mGeometry.size(); // Return updated size
}
std::vector<LayerGeometry::Ptr > Layer::getContourGeometry() const
{
std::vector<LayerGeometry::Ptr> contourGeomList;
for(auto geom : mGeometry) {
if (geom->getType() == LayerGeometry::POLYGON)
contourGeomList.push_back(geom);
}
return contourGeomList;
}
std::vector<LayerGeometry::Ptr > Layer::getHatchGeometry() const
{
std::vector<LayerGeometry::Ptr> geomList;
for(auto geom : mGeometry) {
if (geom->getType() == LayerGeometry::HATCH)
geomList.push_back(geom);
}
return geomList;
}
std::vector<LayerGeometry::Ptr > Layer::getPntsGeometry() const
{
std::vector<LayerGeometry::Ptr> geomList;
for(auto geom : mGeometry) {
if (geom->getType() == LayerGeometry::PNTS)
geomList.push_back(geom);
}
return geomList;
}
std::vector<LayerGeometry::Ptr > Layer::getGeometry(ScanMode mode) const
{
if(mode == HATCH_FIRST ||
mode == CONTOUR_FIRST) {
std::vector<LayerGeometry::Ptr > hatch;
std::vector<LayerGeometry::Ptr > contour;
std::vector<LayerGeometry::Ptr > points;
for(auto it = mGeometry.cbegin(); it != mGeometry.cend(); ++it) {
if((*it)->getType() == LayerGeometry::PNTS) {
points.push_back(*it);
} else if((*it)->getType() == LayerGeometry::POLYGON) {
contour.push_back(*it);
} else if((*it)->getType() == LayerGeometry::HATCH) {
hatch.push_back(*it);
}
}
std::vector<LayerGeometry::Ptr >list;
if(mode == HATCH_FIRST) {
list.insert(list.end(), hatch.begin(), hatch.end());
list.insert(list.end(), contour.begin(), contour.end());
} else {
list.insert(list.end(), contour.begin(), contour.end());
list.insert(list.end(), hatch.begin(), hatch.end());
}
list.insert(list.end(), points.begin(), points.end());
return list;
} else {
return mGeometry;
}
}
namespace slm {
template class LayerGeometryT<LayerGeometry::HATCH>;
template class LayerGeometryT<LayerGeometry::POLYGON>;
template class LayerGeometryT<LayerGeometry::PNTS>;
}
| 4,219
|
C++
|
.cpp
| 147
| 22.163265
| 90
| 0.607507
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,840
|
Utils.cpp
|
drlukeparry_libSLM/App/Utils.cpp
|
#include <codecvt>
#include <locale>
#include "Utils.h"
namespace slm
{
#if _MSC_VER >= 1900
std::string UTF16toASCII(std::u16string utf16_string)
{
std::wstring_convert<std::codecvt_utf8_utf16<int16_t>, int16_t> convert;
auto p = reinterpret_cast<const int16_t *>(utf16_string.data());
return convert.to_bytes(p, p + utf16_string.size());
}
std::u16string ASCIItoUTF16(std::string ascii_string)
{
// see https://riptutorial.com/cplusplus/example/12152/converting-between-character-encodings
using utf16_char = unsigned short;
std::u16string utf16String;
std::wstring_convert<std::codecvt_utf8_utf16<utf16_char>, utf16_char> conv_utf8_utf16;
std::basic_string<utf16_char> tmp = conv_utf8_utf16.from_bytes(ascii_string);
utf16String.clear();
utf16String.resize(tmp.length());
std::copy(utf16String.begin(), utf16String.end(), utf16String.begin());
return utf16String;
}
#else
std::string UTF16toASCII(std::u16string utf16_string)
{
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.to_bytes(utf16_string);
}
std::u16string ASCIItoUTF16(std::string ascii_string)
{
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.from_bytes(ascii_string);
}
#endif
}
| 1,314
|
C++
|
.cpp
| 37
| 32.27027
| 97
| 0.740064
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,540,841
|
Model.cpp
|
drlukeparry_libSLM/App/Model.cpp
|
#include <string>
#include <algorithm>
#include "Utils.h"
#include "Model.h"
using namespace slm;
/*
* Model Definition
*/
BuildStyle::BuildStyle() : id(0),
laserPower(0.0),
laserFocus(0.0),
laserSpeed(0.0),
pointDistance(0),
pointExposureTime(0),
laserId(1),
laserMode(1),
pointDelay(0),
jumpSpeed(0),
jumpDelay(0)
{
}
BuildStyle::~BuildStyle()
{
}
void BuildStyle::setStyle(uint64_t bid,
float focus,
float power,
uint64_t pExpTime,
uint64_t pDistTime,
float speed,
uint64_t lId,
LaserMode lMode)
{
// Convenience function
id = bid;
laserFocus = focus;
laserPower = power;
laserSpeed = speed;
pointExposureTime = pExpTime;
pointDistance = pDistTime;
laserId = lId;
laserMode = lMode;
}
Model::Model() : id(0),
topSliceNum(0)
{
}
Model::Model(uint64_t mid, uint64_t topSliceNum) : id(mid),
topSliceNum(topSliceNum)
{
}
Model::~Model()
{
}
std::string Model::getNameAsString() const
{
return UTF16toASCII(name);
}
std::string Model::getBuildStyleNameAsString() const
{
return UTF16toASCII(buildStyleName);
}
std::string Model::getBuildStlyeDescriptionAsString() const
{
return UTF16toASCII(buildStyleDescription);
}
void Model::clear()
{
this->mBuildStyles.clear();
}
BuildStyle::Ptr Model::getBuildStyleById(const uint64_t bid) const
{
auto result = std::find_if(std::begin(mBuildStyles), std::end(mBuildStyles),
[&](BuildStyle::Ptr bstyle){return bstyle->id == bid;});
if (result != std::end(mBuildStyles)) {
return *result;
} else {
return BuildStyle::Ptr(nullptr);
}
}
int64_t Model::addBuildStyle(BuildStyle::Ptr bstyle)
{
if(!bstyle)
return -1;
auto result = std::find_if(std::begin(mBuildStyles), std::end(mBuildStyles),
[&](BuildStyle::Ptr b){return bstyle->id == b->id;});
if (result != std::end(mBuildStyles))
return -1;
mBuildStyles.push_back(bstyle);
return mBuildStyles.size();
}
#if 0
std::vector<BuildStyle::Ptr> Model::getBuildStyles() const
{
std::vector<BuildStyle::Ptr> bstyles;
bstyles.reserve(buildStyles.size());
// Range iterator
for(auto const& imap: buildStyles)
bstyles.push_back(imap.second);
return bstyles;
}
BuildStyle::Ptr Model::getBuildStyleById(const uint64_t bid) const
{
if(buildStyles.count(bid))
return buildStyles.at(bid);
else
return BuildStyle::Ptr(nullptr);
}
void Model::setBuildStyles(const BStyleMap &bstyles)
{
buildStyles = bstyles;
}
int64_t Model::addBuildStyle(BuildStyle::Ptr bstyle)
{
if(!bstyle)
return -1;
if(!buildStyles.count(bstyle->id))
buildStyles.insert(BStyleMap::value_type(bstyle->id, bstyle));
return buildStyles.size();
}
#endif
| 3,312
|
C++
|
.cpp
| 121
| 19.61157
| 85
| 0.582198
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,842
|
utils.h
|
drlukeparry_libSLM/python/libSLM/utils.h
|
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <pybind11/functional.h>
#include <pybind11/complex.h>
#include <pybind11/eigen.h>
#include <algorithm>
namespace py = pybind11;
namespace slm {
template <typename Vector, typename holder_type = std::unique_ptr<Vector>>
py::class_<Vector, holder_type> bind_my_vector(py::handle scope, std::string const &name) {
using Class_ = py::class_<Vector, holder_type>;
// If the value_type is unregistered (e.g. a converting type) or is itself registered
// module-local then make the vector binding module-local as well:
using vtype = typename Vector::value_type;
using SizeType = typename Vector::size_type;
using DiffType = typename Vector::difference_type;
auto wrap_i = [](DiffType i, SizeType n) {
if (i < 0)
i += n;
if (i < 0 || (SizeType)i >= n)
throw py::index_error();
return i;
};
Class_ cl(scope, name.c_str());
cl.def(py::init<>())
.def(py::init([](py::iterable it) {
auto v = std::unique_ptr<Vector>(new Vector());
v->reserve(len_hint(it));
for (py::handle h : it)
v->push_back(h.cast<vtype>());
return v.release();
}))
.def(py::init<const Vector &>(), "Copy constructor");
/* TODO - check if above requires py::keep_alive */
cl.def(py::self == py::self)
.def(py::self != py::self);
cl.def("clear", &Vector::clear)
.def("append", (void (Vector::*)(const vtype &)) &Vector::push_back, py::keep_alive<1, 2>());
cl.def("pop_back", &Vector::pop_back)
.def("__len__", &Vector::size)
.def("__bool__", &Vector::empty);
cl.def("count",
[](const Vector &v, const vtype &x) {
return std::count(v.begin(), v.end(), x);
},
py::arg("x"),
"Return the number of times ``x`` appears in the list"
);
cl.def("remove", [](Vector &v, const vtype &x) {
auto p = std::find(v.begin(), v.end(), x);
if (p != v.end())
v.erase(p);
else
throw py::value_error();
},
py::arg("x"),
"Remove the first item from the list whose value is x. "
"It is an error if there is no such item."
);
// Iteration methods
cl.def("__getitem__",
[](const Vector &v, DiffType i) -> vtype {
if (i < 0 && (i += v.size()) < 0)
throw py::index_error();
if ((SizeType)i >= v.size())
throw py::index_error();
return v[(SizeType)i];
}
);
cl.def("__iter__", [](Vector &v) {
return py::make_iterator(v.begin(), v.end());
}, py::keep_alive<0, 1>()); /* Keep vector alive while iterator is used */
cl.def("__contains__",
[](const Vector &v, const vtype &x) {
return std::find(v.begin(), v.end(), x) != v.end();
},
py::arg("x"),
"Return true the container contains ``x``"
);
/// Slicing protocol
cl.def("__getitem__",
[](const Vector &v, py::slice slice) -> Vector * {
size_t start, stop, step, slicelength;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
throw py::error_already_set();
Vector *seq = new Vector();
seq->reserve((size_t) slicelength);
for (size_t i=0; i<slicelength; ++i) {
seq->push_back(v[start]);
start += step;
}
return seq;
},
py::arg("s"),
"Retrieve list elements using a slice object"
);
// Modifiers
cl.def("__setitem__",
[wrap_i](Vector &v, DiffType i, const vtype &t) {
i = wrap_i(i, v.size());
v[(SizeType)i] = t;
}, py::keep_alive<1, 2>()
);
cl.def("__setitem__",
[](Vector &v, py::slice slice, const Vector &value) {
size_t start, stop, step, slicelength;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
throw py::error_already_set();
if (slicelength != value.size())
throw std::runtime_error("Left and right hand size of slice assignment have different sizes!");
for (size_t i=0; i<slicelength; ++i) {
v[start] = value[i];
start += step;
}
},
"Assign list elements using a slice object",
py::keep_alive<1, 2>()
);
cl.def("__delitem__",
[wrap_i](Vector &v, DiffType i) {
i = wrap_i(i, v.size());
v.erase(v.begin() + i);
},
"Delete the list elements at index ``i``"
);
cl.def("__delitem__",
[](Vector &v, py::slice slice) {
size_t start, stop, step, slicelength;
if (!slice.compute(v.size(), &start, &stop, &step, &slicelength))
throw py::error_already_set();
if (step == 1 && false) {
v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
} else {
for (size_t i = 0; i < slicelength; ++i) {
v.erase(v.begin() + DiffType(start));
start += step - 1;
}
}
},
"Delete list elements using a slice object"
);
cl.def("extend",
[](Vector &v, const Vector &src) {
v.insert(v.end(), src.begin(), src.end());
},
py::arg("L"),
"Extend the list by appending all the items in the given list"
);
cl.def("extend",
[](Vector &v, py::iterable it) {
const size_t old_size = v.size();
v.reserve(old_size + len_hint(it));
try {
for (py::handle h : it) {
v.push_back(h.cast<vtype>());
}
} catch (const py::cast_error &) {
v.erase(v.begin() + static_cast<typename Vector::difference_type>(old_size), v.end());
try {
v.shrink_to_fit();
} catch (const std::exception &) {
// Do nothing
}
throw;
}
},
py::arg("L"),
"Extend the list by appending all the items in the given list"
);
cl.def(py::pickle(
[](const Vector &v) { // __getstate__
/* Return a tuple that fully encodes the state of the object */
py::list list;
for(vtype x : v)
list.append(x);
return list;
}, [](const py::list &t) {
auto v = std::unique_ptr<Vector>(new Vector());
v->reserve(t.size());
for(py::handle h : t)
v->push_back(h.cast<vtype>());
return v;
}
));
return cl;
}
}
| 7,188
|
C++
|
.h
| 190
| 26.857895
| 111
| 0.485681
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,843
|
Reader.h
|
drlukeparry_libSLM/App/Reader.h
|
#ifndef BASE_READER_H_HEADER_HAS_BEEN_INCLUDED
#define BASE_READER_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <string>
#include "Layer.h"
#include "Model.h"
namespace slm
{
namespace base
{
class SLM_EXPORT Reader
{
public:
Reader(const std::string &buildFile);
Reader();
virtual ~Reader();
public:
virtual int parse() = 0;
bool isReady() const { return ready; }
std::string getFilePath() { return filePath; }
void setFilePath(std::string path);
int64_t getFileSize() const;
virtual double getLayerThickness() const = 0;
Model::Ptr getModelById(uint64_t mid) const;
std::vector<Model::Ptr> getModels() const { return models;}
std::vector<Layer::Ptr> getLayers() const { return layers;}
Layer::Ptr getTopLayerByPosition(const std::vector<Layer::Ptr> &layers);
Layer::Ptr getTopLayerById(const std::vector<Layer::Ptr> &layers);
protected:
void setReady(bool state) { ready = state; }
std::string filePath;
protected:
std::vector<Model::Ptr> models;
std::vector<Layer::Ptr> layers;
private:
bool ready;
};
}
} // End of Namespace Base
#endif // BASE_READER_H_HEADER_HAS_BEEN_INCLUDED
| 1,203
|
C++
|
.h
| 40
| 26.45
| 76
| 0.716049
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,844
|
Header.h
|
drlukeparry_libSLM/App/Header.h
|
#ifndef SLM_HEADER_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_HEADER_H_HEADER_HAS_BEEN_INCLUDED
#include <string>
#include <tuple>
namespace slm {
// Forward declaration
struct Header
{
std::string fileName;
std::string creator;
void setVersion(std::tuple<int,int> version) { std::tie(vMajor, vMinor) = version; }
std::tuple<int, int> version() const { return std::make_tuple(vMajor, vMinor); }
int vMajor;
int vMinor;
int zUnit;
};
} //SLM_HEADER_H_HEADER_HAS_BEEN_INCLUDED
#endif // SLM_HEADER_H_HEADER_HAS_BEEN_INCLUDED
| 555
|
C++
|
.h
| 18
| 27.833333
| 88
| 0.724008
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,845
|
Iterator.h
|
drlukeparry_libSLM/App/Iterator.h
|
#ifndef SLM_ITERATOR_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_ITERATOR_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <Eigen/Dense>
#include "Layer.h"
#include "Slm.h"
namespace slm
{
class Layer;
// Current state of laser power at time t
struct State
{
bool laserOn;
float power; // Laser Power (W)
int pntExposureTime; // Point Exposure Time (ms)
int pntDistance; // Point Distance (microm)
inline float laserSpeed() { return (float) pntDistance * 1. / (float) pntExposureTime; }
Eigen::Vector2f position; // s = (x,y)'
Eigen::Vector2f velocity; // v = (u,v)' // Note w is zero
uint layer;
double time; // Current time
};
struct LaserScan
{
Eigen::Vector2f start;
Eigen::Vector2f end;
double tStart;
double tEnd;
uint layer;
LayerGeometry::TYPE type;
};
class SLM_EXPORT Iterator
{
public:
typedef Slm::node node;
Iterator(Slm *val);
Iterator();
~Iterator();
void setTimeIncrement(double val) { _timeInc = val; }
public:
void seek(const double &time);
void seekLayer(const int &layerNum);
Iterator& operator++(); // Prefix increment operator.
Iterator operator++(int); // Postfix increment operator.
bool more() const;
void next();
State value() const;
int getCurrentLayerNumber() const;
Layer::Ptr getCurrentLayer() const;
// Add operator ++ to increment automtically
protected:
Slm::Ptr obj; // TODO make a smart pointer
double _inc; // Current increment
double _endTime;
double _timeInc; // The finite time difference to iterate with
int _layerInc; // Layer increment
int _layerGeomInc; // Layer Geometry Increment for current layer
};
class SLM_EXPORT LayerIterator: public Iterator
{
public:
LayerIterator(Slm *val, int layerId);
~LayerIterator();
private:
double _layerTime;
};
class SLM_EXPORT LayerGeomIterator : public Iterator
{
public:
LayerGeomIterator(Slm::Ptr val);
~LayerGeomIterator();
public:
void seek(const double &time);
void seekLayer(const int &layerNum);
int getCurrentLayerNumber() const;
Layer::Ptr getCurrentLayer() const;
double getCurrentTime() const;
LayerGeomIterator& operator++(); // Prefix increment operator.
LayerGeomIterator operator++(int); // Postfix increment operator.
LayerGeometry getLayerGeometry() const;
bool more() const;
void next();
LayerGeometry value() const;
private:
std::vector<Layer::Ptr>::const_iterator _layerIt; // Current Layer Iterator
std::vector<LayerGeometry::Ptr> _layerGeomCache;
std::vector<Layer::Ptr> _layerCache;
std::vector<LayerGeometry>::const_iterator _layerGeomIt; // Current Layer Geometry Iterator
};
class SLM_EXPORT LaserScanIterator : public LayerGeomIterator
{
public:
LaserScanIterator(Slm *val);
~LaserScanIterator();
public:
LaserScanIterator& operator++(); // Prefix increment operator.
LaserScanIterator operator++(int); // Postfix increment operator.
void next();
double getCurrentTime() const;
bool more() const;
LaserScan value() const;
private:
double calcScanTime() const;
double _layerGeomTime,
_relTime; // Relative time
LayerGeometry _curLayerGeom;
QVector<QPointF>::const_iterator _pntIt; // Laser Point Iterator
};
} // End of namespace SLM
#endif // SLM_ITERATOR_H_HEADER_HAS_BEEN_INCLUDED
| 3,536
|
C++
|
.h
| 110
| 28.254545
| 95
| 0.689177
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,846
|
Layer.h
|
drlukeparry_libSLM/App/Layer.h
|
#ifndef SLM_LAYER_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_LAYER_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <cstdint>
#include <vector>
#include <memory>
#include <Eigen/Dense>
namespace slm
{
enum ScanMode {
NONE = 0,
CONTOUR_FIRST = 1,
HATCH_FIRST = 2
};
/**
* @brief The LayerGeometry base class describes geometry information for each layer
*/
class SLM_EXPORT LayerGeometry
{
public:
typedef std::shared_ptr<LayerGeometry> Ptr;
LayerGeometry(uint32_t modelId, uint32_t buildStyleId );
LayerGeometry();
virtual ~LayerGeometry();
public:
enum TYPE {
INVALID = 0,
POLYGON = 1,
HATCH = 2,
PNTS = 3
};
Eigen::MatrixXf coords;
protected:
uint32_t modelId = 0;
uint32_t buildId = 0;
public:
uint32_t mid = 0;
uint32_t bid = 0;
// Type may only be set upon initialisation
virtual TYPE getType() const { return type; }
public:
const static TYPE type = INVALID;
};
template <LayerGeometry::TYPE T>
class SLM_EXPORT LayerGeometryT : public LayerGeometry
{
public:
typedef std::shared_ptr<LayerGeometryT> Ptr;
LayerGeometryT() {}
LayerGeometryT(uint32_t modelId, uint32_t buildStyleId) : LayerGeometry(modelId, buildStyleId) {}
~LayerGeometryT() {}
public:
const static TYPE type = T;
virtual TYPE getType() const { return type; }
};
class SLM_EXPORT Layer
{
public:
typedef std::shared_ptr<Layer> Ptr;
Layer();
Layer(uint64_t id, uint64_t zVal);
~Layer();
public:
void clear();
/**
* Setters
*/
void setLayerId(const uint64_t &id);
void setZ(const uint64_t &val);
void setLayerFilePosition(const uint64_t &position);
void setIsLoaded(const bool &isLoaded);
// Add different types of geometry to each layer
template <class T>
int64_t addGeometry(typename T::Ptr geom) {
if(!geom)
return -1;
mGeometry.push_back(geom);
return mGeometry.size();
}
void appendGeometry(LayerGeometry::Ptr geom);
int64_t addContourGeometry(LayerGeometry::Ptr geom);
int64_t addHatchGeometry(LayerGeometry::Ptr geom);
int64_t addPntsGeometry(LayerGeometry::Ptr geom);
const std::vector<LayerGeometry::Ptr> & geometry() const { return mGeometry; }
std::vector<LayerGeometry::Ptr> & geometryRef() { return mGeometry; }
void setGeometry(const std::vector<LayerGeometry::Ptr> &geoms);
template <class T>
std::vector<LayerGeometry::Ptr> getGeometryByType () {
std::vector<LayerGeometry::Ptr> geoms;
for(LayerGeometry::Ptr geom : mGeometry) {
if(geom->getType() == T::type){geoms.push_back(geom);}
}
return geoms;
}
std::vector<LayerGeometry::Ptr> getGeometry(ScanMode mode = NONE) const;
std::vector<LayerGeometry::Ptr> getContourGeometry() const;
std::vector<LayerGeometry::Ptr> getHatchGeometry() const;
std::vector<LayerGeometry::Ptr> getPntsGeometry() const;
/**
* Getters
*/
uint64_t layerFilePosition() const { return mLayerPos; }
uint64_t getZ() const { return z; }
uint64_t getLayerId() const { return lid; }
bool isLoaded() const { return mIsLoaded; }
protected:
uint64_t lid = 0; // Layer ID
uint64_t z = 0; // Z Layer Position
uint64_t mLayerPos;
std::vector<LayerGeometry::Ptr> mGeometry;
bool mIsLoaded;
};
using HatchGeometry = slm::LayerGeometryT<LayerGeometry::HATCH>;
using ContourGeometry = slm::LayerGeometryT<LayerGeometry::POLYGON>;
using PntsGeometry = slm::LayerGeometryT<LayerGeometry::PNTS>;
} // End of Namespace slm
#endif // SLM_LAYER_H_HEADER_HAS_BEEN_INCLUDED
| 3,725
|
C++
|
.h
| 117
| 27.264957
| 101
| 0.684978
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,847
|
Model.h
|
drlukeparry_libSLM/App/Model.h
|
#ifndef SLM_MODEL_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_MODEL_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace slm
{
enum LaserMode {
CW = 0,
PULSE = 1
};
class SLM_EXPORT BuildStyle
{
// Model can access protected data/methods
friend class Model;
public:
typedef std::shared_ptr<BuildStyle> Ptr;
BuildStyle();
~BuildStyle();
void setStyle(uint64_t bid,
float focus,
float power,
uint64_t pExpTime,
uint64_t pDistTime,
float speed = 0.f,
uint64_t laserId = 1,
LaserMode laserMode = LaserMode::PULSE);
void setName(const std::u16string &str) { name = str;}
void setDescription(const std::u16string &str) { description = str;}
public:
uint64_t id;
uint64_t laserId;
uint64_t laserMode;
float laserPower;
float laserFocus;
float laserSpeed;
uint64_t pointDistance;
uint64_t pointDelay;
uint64_t pointExposureTime;
uint64_t jumpSpeed;
uint64_t jumpDelay;
std::u16string name;
std::u16string description;
};
class SLM_EXPORT Model
{
public:
Model();
Model(uint64_t mid, uint64_t topSliceNum);
~Model();
public:
typedef std::shared_ptr<Model> Ptr;
typedef std::map<uint64_t, BuildStyle::Ptr> BStyleMap;
enum BuildStyleID
{
CoreContour_Volume = 1, /** core contour on volume */
CoreContour_Overhang = 2, /** core contour on powder */
HollowShell1Contour_Volume = 3,/** shell1 contour on volume */
HollowShell1Contour_Overhang = 4,/** shell1 contour on powder */
HollowShell2Contour_Volume = 5,/** shell2 contour on volume */
HollowShell2Contour_Overhang = 6,/** shell2 contour on powder */
CoreOverhangHatch = 7, /** core hatch on powder */
CoreNormalHatch = 8, /** core hatch on volume */
CoreContourHatch = 9, /** core contour hatch */
HollowShell1OverhangHatch = 10, /** shell1 hatch on powder */
HollowShell1NormalHatch = 11, /** shell1 hatch on volume */
HollowShell1ContourHatch = 12, /** shell1 contour hatch */
HollowShell2OverhangHatch = 13, /** shell2 hatch on powder */
HollowShell2NormalHatch = 14, /** shell2 hatch on volume */
HollowShell2ContourHatch = 15, /** shell2 contour hatch */
SupportContourVolume = 16, /** support contour */
SupportHatch = 17, /** support hatch */
PointSequence = 18, /** point sequence */
ExternalSupports = 19, /** Externe Stützen */
CoreContourHatchOverhang = 20, /** HollowCore Konturversatz - Overhang */
HollowShell1ContourHatchOverhang = 21, /** HollowShell1 - Overhang */
HollowShell2ContourHatchOverhang = 22, /** HollowShell2 Konturversatz - Overhang */
};
void clear();
/**
* Getters
*/
uint64_t getId() const { return id;}
uint64_t getTopSlice() const { return topSliceNum; }
std::u16string getName() const { return name; }
std::string getNameAsString() const;
std::u16string getBuildStyleName() const { return buildStyleName; }
std::string getBuildStyleNameAsString() const;
std::u16string getBuildStyleDescription() const { return buildStyleDescription; }
std::string getBuildStlyeDescriptionAsString() const;
/*
* Build Style Getters
*/
void setBuildStyles(const std::vector<BuildStyle::Ptr> &bstyles) { mBuildStyles = bstyles; }
std::vector<BuildStyle::Ptr> getBuildStyles() const { return mBuildStyles; }
BuildStyle::Ptr getBuildStyleById(const uint64_t bid) const;
std::vector<BuildStyle::Ptr> & buildStylesRef() { return mBuildStyles; }
/**
* Setters
*/
int64_t addBuildStyle(BuildStyle::Ptr bstyle);
//void setBuildStyles(const BStyleMap &bstyles);
void setId(const uint64_t val) { id = val;}
void setTopSlice(const uint64_t val) { topSliceNum = val;}
void setName(const std::u16string &str) { name = str;}
void setBuildStlyeName(const std::u16string &str) { buildStyleName = str;}
void setBuildStlyeDescription(const std::u16string &str) { buildStyleDescription = str;}
protected:
uint64_t id;
uint64_t topSliceNum;
std::u16string name;
std::u16string buildStyleName;
std::u16string buildStyleDescription;
//BStyleMap buildStyles;
std::vector<BuildStyle::Ptr> mBuildStyles;
};
} // End of SLM Namespace
#endif // SLM_MODEL_H_HEADER_HAS_BEEN_INCLUDED
| 4,807
|
C++
|
.h
| 121
| 33.595041
| 97
| 0.645175
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,848
|
Utils.h
|
drlukeparry_libSLM/App/Utils.h
|
#ifndef SLM_UTILS_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_UTILS_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <string>
#include <codecvt>
#include <locale>
namespace slm {
// Forward declaration
SLM_EXPORT std::string UTF16toASCII(std::u16string utf16_string);
SLM_EXPORT std::u16string ASCIItoUTF16(std::string ascii_string);
} //
#endif // SLM_UTILS_H_HEADER_HAS_BEEN_INCLUDED
| 404
|
C++
|
.h
| 12
| 31.666667
| 65
| 0.789474
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,849
|
Writer.h
|
drlukeparry_libSLM/App/Writer.h
|
#ifndef BASE_WRITER_H_HEADER_HAS_BEEN_INCLUDED
#define BASE_WRITER_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <string>
#include "Header.h"
#include "Layer.h"
#include "Model.h"
namespace slm
{
namespace base
{
class SLM_EXPORT Writer
{
public:
Writer(const char *fileLoc);
Writer(const std::string &fileLoc);
Writer();
virtual ~Writer();
public:
bool isReady() const { return ready; }
const std::string & getFilePath() { return filePath; }
void setFilePath( const std::string &path);
virtual void write(const Header &header,
const std::vector<Model::Ptr> &models,
const std::vector<Layer::Ptr> &layers) = 0;
bool isSortingLayers() const { return mSortLayers; }
void setSortLayers(bool state) { mSortLayers = state; }
public:
static void getBoundingBox(float *bbox, const std::vector<Layer::Ptr> &layers);
static void getLayerBoundingBox(float *bbox, Layer::Ptr layer);
static std::tuple<float, float> getLayerMinMax(const std::vector<slm::Layer::Ptr> &layers);
static Layer::Ptr getTopLayerByPosition(const std::vector<Layer::Ptr> &layers);
static Layer::Ptr getTopLayerById(const std::vector<Layer::Ptr> &layers);
static int64_t getTotalNumHatches(const std::vector<Layer::Ptr> &layers);
static int64_t getTotalNumContours(const std::vector<Layer::Ptr> &layers);
static std::vector<Layer::Ptr> sortLayers(const std::vector<Layer::Ptr> &layers);
template <class T>
static int64_t getTotalGeoms(const std::vector<slm::Layer::Ptr> &layers)
{
int64_t numGeomT = 0;
for(auto layer : layers)
numGeomT += layer->getGeometryByType<T>().size();
return numGeomT;
}
protected:
void setReady(bool state) { ready = state; }
void getFileHandle(std::fstream &file) const;
protected:
std::string filePath;
private:
bool ready;
bool mSortLayers;
};
} // End of Namespace Base
} // End of Namespace Base
#endif // BASE_WRITER_H_HEADER_HAS_BEEN_INCLUDED
| 2,085
|
C++
|
.h
| 56
| 32.089286
| 96
| 0.691962
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,850
|
Slm.h
|
drlukeparry_libSLM/App/Slm.h
|
#ifndef SLM_SLM_H_HEADER_HAS_BEEN_INCLUDED
#define SLM_SLM_H_HEADER_HAS_BEEN_INCLUDED
#include "SLM_Export.h"
#include <cfloat>
#include <vector>
#include <Base/Tree.h>
#include "Layer.h"
#include "Model.h"
namespace slm {
// Forward declaration
class Iterator;
class GenLayerIndex;
}
namespace slm
{
class SLM_EXPORT Slm
{
public:
Slm();
~Slm();
friend class Iterator;
friend struct GenLayerIndex;
public:
typedef base::Tree<uint64_t, double> tree;
typedef base::Node<uint64_t, double> node;
//typedef boost::property_tree::ptree tree;
// Setters and Getters for manipulating the time between layers.
void setLayerCoolingTime(const double &t) { this->layerCoolingTime = t; }
void setLayerAdditionTime(const double &t) { this->layerAdditionTime = t; }
inline double getLayerCoolingTime() const { return layerCoolingTime; }
inline double getLayerAdditionTime() const { return layerAdditionTime; }
void setBuild(const std::vector<Layer::Ptr> &layers,
const std::vector<Model::Ptr> &models,
ScanMode mode,
const double lThickness,
const double lAdditionTime = 0.,
const double lCoolingTime = 0.);
void clear();
inline tree getTimeIndex() const { return this->tindex;}
/**
* Layer Information
*/
inline double getLayerThickness() const { return this->layerThickness;}
int getLayerIdByTime(const double &t) const ;
Layer::Ptr getLayerByTime(const double &t) const;
double getTimeByLayerId(const int layerId) const;
double getTimeByLayerGeomId(const int layerId, const int geomId) const;
/**
* @param t - Current Time (s)
* @param x - Laser Position on current layer
* @param y - Laser Position on current layer
* @param z - Laser Position based on current layer and it's thickness
* @param isLaserOn - Determines if the laser is currently on (e.g. addition of powder layer)
*/
void getLaserPosition(const double &t, double &x, double &y, double &z, bool &isLaserOn) const;
/**
* @param t - Current Time (s)
* @param power - Laser Power (W)
* @param expTime - Laser Exposure Time (ms)
* @param pntDist - Laser Point Distance (microns)
* @param isLaserOn - Determines if the laser is currently on (e.g. addition of powder layer)
*/
void getLaserParameters(const double &t, float &power, int &expTime, int &pntDist, bool &isLaserOn) const;
/**
* @param t - Current Time (s)
* @param deltaX - Current X Velocity for laser
* @param deltaY - Curreny Y Velocity for laser
* @param pntDist - Laser Point Distance
* @param isLaserOn - Determines if the laser is currently on (e.g. addition of powder layer)
*/
void getLaserVelocity(const double &t, double &deltaX, double &deltaY, bool &isLaserOn) const;
bool isLaserOnByTime(const double t) const;
/**
* @brief getLayerGeometryByTime
* @param t - Current Tmime
* @return LayerGeometry * - the current Layer Geometry at time t
*/
LayerGeometry::Ptr getLayerGeometryByTime(const double t) const;
// Information for build
double getBuildTime() const;
double getBuildEnergy() const;
const std::vector<Layer::Ptr> & getLayers() const { return layers; }
const std::vector<Model::Ptr> & getModels() const { return models;}
inline ScanMode getScanMode() const { return scanmode; }
Model::Ptr getModelById(uint id) const;
protected:
void rebuildCache();
void invalidateCache();
void parseGeometry();
void createLayerIndex();
void getPointsInGeom(const double &offset, LayerGeometry *lgeom, QPointF &p1, QPointF &p2) const;
QPointF getPointInGeom(const double &offset, LayerGeometry *lgeom) const;
double calcGeomTime(LayerGeometry *lgeom) const;
protected:
tree tindex;
// Convenience helper function to check if time is within bounds
bool isBoundByTimeInterval(const double t, const double sTime, const double delta) const {
return t > sTime - DBL_EPSILON && t < sTime + delta - DBL_EPSILON;
}
double layerThickness;
double layerAdditionTime; // Time taken for new layer of powder to be added
double layerCoolingTime; // Time after last laser scan for layer to cool
ScanMode scanmode;
std::vector<Layer::Ptr> layers;
std::vector<Model::Ptr> models;
private:
tree _cache;
};
} // end of namespace slm
#endif // SLM_SLM_H_HEADER_HAS_BEEN_INCLUDED
| 4,597
|
C++
|
.h
| 110
| 36.227273
| 110
| 0.690546
|
drlukeparry/libSLM
| 30
| 5
| 4
|
LGPL-2.1
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,851
|
message_widget.cpp
|
olegkapitonov_spiceAmp/src/message_widget.cpp
|
/*
* Copyright (C) 2018-2020 Oleg Kapitonov
*
* 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 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* --------------------------------------------------------------------------
*/
#include <QVBoxLayout>
#include "message_widget.h"
MessageWidget::MessageWidget(QWidget *parent) : QDialog(parent)
{
setMinimumWidth(400);
setMinimumHeight(80);
QVBoxLayout *lay = new QVBoxLayout(this);
messageLabel = new QLabel(this);
lay->addWidget(messageLabel);
messageLabel->setAlignment(Qt::AlignCenter);
}
void MessageWidget::setTitle(QString title)
{
setWindowTitle(title);
}
void MessageWidget::setMessage(QString message)
{
messageLabel->setText(message);
}
| 1,338
|
C++
|
.cpp
| 37
| 34.081081
| 80
| 0.727975
|
olegkapitonov/spiceAmp
| 30
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,852
|
main.cpp
|
olegkapitonov_spiceAmp/src/main.cpp
|
/*
* Copyright (C) 2018-2020 Oleg Kapitonov
*
* 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 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* --------------------------------------------------------------------------
*/
#include <QApplication>
#include <QStyle>
#include <QDesktopWidget>
#include <QScreen>
#include <QDir>
#include "mainwindow.h"
bool copy_dir_recursive(QString from_dir, QString to_dir, bool replace_on_conflit)
{
QDir dir;
dir.setPath(from_dir);
from_dir += QDir::separator();
to_dir += QDir::separator();
foreach (QString copy_file, dir.entryList(QDir::Files))
{
QString from = from_dir + copy_file;
QString to = to_dir + copy_file;
if (QFile::exists(to))
{
if (replace_on_conflit)
{
if (QFile::remove(to) == false)
{
return false;
}
}
else
{
continue;
}
}
if (QFile::copy(from, to) == false)
{
return false;
}
}
foreach (QString copy_dir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
{
QString from = from_dir + copy_dir;
QString to = to_dir + copy_dir;
if (dir.mkpath(to) == false)
{
return false;
}
if (copy_dir_recursive(from, to, replace_on_conflit) == false)
{
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QCoreApplication::setOrganizationName("Oleg Kapitonov");
QCoreApplication::setApplicationName("spiceAmp");
QDir shareDir(QCoreApplication::applicationDirPath());
shareDir.cdUp();
shareDir.cd("share/spiceAmp");
QDir workDir(QDir::homePath() + "/spiceAmp Data");
if (!workDir.exists())
{
workDir.cdUp();
workDir.mkdir("spiceAmp Data");
workDir.cd("spiceAmp Data");
copy_dir_recursive(shareDir.absolutePath(), workDir.absolutePath(), false);
}
MainWindow w(nullptr);
w.setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
w.size(),
qApp->screens()[0]->availableGeometry()
)
);
w.show();
return a.exec();
}
| 2,719
|
C++
|
.cpp
| 96
| 24.166667
| 82
| 0.652975
|
olegkapitonov/spiceAmp
| 30
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,540,853
|
mainwindow.cpp
|
olegkapitonov_spiceAmp/src/mainwindow.cpp
|
/*
* Copyright (C) 2018-2020 Oleg Kapitonov
*
* 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 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* --------------------------------------------------------------------------
*/
#include <QFileDialog>
#include <QVector>
#include <QMessageBox>
#include <QSettings>
#include "mainwindow.h"
#include "math_functions.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
processor = new ProcessorThread(this);
statusBox = new MessageWidget(this);
statusBox->setTitle("Processing...");
ui.setupUi(this);
}
void MainWindow::on_exitButton_clicked()
{
close();
}
void MainWindow::on_diButton_clicked()
{
QString lastPath = loadLastPath();
QString diFileName = QFileDialog::getOpenFileName(this,
"Open DI File",
lastPath,
"Sound files (*.wav *.ogg *.flac)");
if (!diFileName.isEmpty())
{
ui.diFilenameEdit->setText(diFileName);
saveLastPath(QFileInfo(diFileName).absolutePath());
}
checkFilenames();
}
void MainWindow::on_spiceButton_clicked()
{
QString lastPath = loadLastPath();
QString spiceFileName = QFileDialog::getOpenFileName(this,
"Open SPICE Model File",
lastPath,
"SPICE circuit (*.cir)");
if (!spiceFileName.isEmpty())
{
ui.spiceFilenameEdit->setText(spiceFileName);
saveLastPath(QFileInfo(spiceFileName).absolutePath());
}
checkFilenames();
}
void MainWindow::on_IRButton_clicked()
{
QString lastPath = loadLastPath();
QString IRFileName = QFileDialog::getOpenFileName(this,
"Open Cabinet Impulse Response",
lastPath,
"Sound files (*.wav *.ogg *.flac)");
if (!IRFileName.isEmpty())
{
ui.IRFilenameEdit->setText(IRFileName);
saveLastPath(QFileInfo(IRFileName).absolutePath());
}
checkFilenames();
}
void MainWindow::on_outputButton_clicked()
{
QString lastPath = loadLastPath();
QString outputFileName = QFileDialog::getSaveFileName(this,
"Save Processed Sound",
lastPath,
"Sound files (*.wav *.ogg *.flac)");
if (!outputFileName.isEmpty())
{
ui.outputFilenameEdit->setText(outputFileName);
saveLastPath(QFileInfo(outputFileName).absolutePath());
}
checkFilenames();
}
void MainWindow::on_normalizeSlider_valueChanged(int value)
{
QString labelText = QString("%1 mV").arg(value);
ui.normalizeLabel->setText(labelText);
}
void MainWindow::checkFilenames()
{
if (!((ui.IRFilenameEdit->text().isEmpty() && !ui.withoutCabinetCheckBox->isChecked()) ||
ui.spiceFilenameEdit->text().isEmpty() ||
ui.diFilenameEdit->text().isEmpty() ||
ui.outputFilenameEdit->text().isEmpty()
))
{
ui.processButton->setEnabled(true);
}
}
void MainWindow::on_processButton_clicked()
{
processor->diFilename = ui.diFilenameEdit->text();
processor->diNormalize = (double)ui.normalizeSlider->value() / 1000.0;
processor->spiceFilename = ui.spiceFilenameEdit->text();
processor->withoutCabinet = ui.withoutCabinetCheckBox->isChecked();
processor->IRFilename = ui.IRFilenameEdit->text();
processor->outputFilename = ui.outputFilenameEdit->text();
processor->msg = statusBox;
processor->start();
statusBox->open();
}
void MainWindow::on_withoutCabinetCheckBox_stateChanged(int state)
{
if (state == Qt::Unchecked)
{
ui.IRFilenameEdit->setEnabled(true);
ui.IRButton->setEnabled(true);
}
else
{
ui.IRFilenameEdit->setEnabled(false);
ui.IRButton->setEnabled(false);
}
checkFilenames();
}
void MainWindow::on_processor_finished()
{
statusBox->close();
}
void MainWindow::on_processor_processorSuccess()
{
QMessageBox::information(0, "Info", "Processing finished succesfully!");
}
void MainWindow::on_processor_processorError(QString error)
{
QMessageBox::critical(0, "error", error);
}
void MainWindow::saveLastPath(QString path)
{
QSettings settings;
settings.setValue("dialog/lastPath", path);
}
QString MainWindow::loadLastPath()
{
QSettings settings;
return settings.value("dialog/lastPath", QDir::homePath() + "/spiceAmp Data/Models").toString();
}
void MainWindow::on_diFilenameEdit_textEdited(QString)
{
checkFilenames();
}
void MainWindow::on_spiceFilenameEdit_textEdited(QString)
{
checkFilenames();
}
void MainWindow::on_IRFilenameEdit_textEdited(QString)
{
checkFilenames();
}
void MainWindow::on_outputFilenameEdit_textEdited(QString)
{
checkFilenames();
}
| 5,559
|
C++
|
.cpp
| 171
| 26.467836
| 98
| 0.655836
|
olegkapitonov/spiceAmp
| 30
| 4
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.