text
stringlengths
54
60.6k
<commit_before>// Copyright 2022 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <grpc/support/port_platform.h> #include "src/core/lib/event_engine/forkable.h" #ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK #include <pthread.h> #include "absl/container/flat_hash_set.h" #include "src/core/lib/gprpp/no_destruct.h" #include "src/core/lib/gprpp/sync.h" namespace grpc_event_engine { namespace experimental { namespace { grpc_core::NoDestruct<grpc_core::Mutex> g_mu; bool g_registered ABSL_GUARDED_BY(g_mu){false}; grpc_core::NoDestruct<absl::flat_hash_set<Forkable*>> g_forkables ABSL_GUARDED_BY(g_mu); } // namespace Forkable::Forkable() { ManageForkable(this); } Forkable::~Forkable() { StopManagingForkable(this); } void RegisterForkHandlers() { grpc_core::MutexLock lock(g_mu.get()); GPR_ASSERT(!absl::exchange(g_registered, true)); pthread_atfork(PrepareFork, PostforkParent, PostforkChild); }; void PrepareFork() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PrepareFork(); } } void PostforkParent() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PostforkParent(); } } void PostforkChild() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PostforkChild(); } } void ManageForkable(Forkable* forkable) { grpc_core::MutexLock lock(g_mu.get()); g_forkables->insert(forkable); } void StopManagingForkable(Forkable* forkable) { grpc_core::MutexLock lock(g_mu.get()); g_forkables->erase(forkable); } } // namespace experimental } // namespace grpc_event_engine #else // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK namespace grpc_event_engine { namespace experimental { Forkable::Forkable() {} Forkable::~Forkable() {} void RegisterForkHandlers() {} void PrepareFork() {} void PostforkParent() {} void PostforkChild() {} void ManageForkable(Forkable* /* forkable */) {} void StopManagingForkable(Forkable* /* forkable */) {} } // namespace experimental } // namespace grpc_event_engine #endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK <commit_msg>Fix forkable repeated registration (#30642)<commit_after>// Copyright 2022 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <grpc/support/port_platform.h> #include "src/core/lib/event_engine/forkable.h" #ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK #include <pthread.h> #include "absl/container/flat_hash_set.h" #include "src/core/lib/gprpp/no_destruct.h" #include "src/core/lib/gprpp/sync.h" namespace grpc_event_engine { namespace experimental { namespace { grpc_core::NoDestruct<grpc_core::Mutex> g_mu; bool g_registered ABSL_GUARDED_BY(g_mu){false}; grpc_core::NoDestruct<absl::flat_hash_set<Forkable*>> g_forkables ABSL_GUARDED_BY(g_mu); } // namespace Forkable::Forkable() { ManageForkable(this); } Forkable::~Forkable() { StopManagingForkable(this); } void RegisterForkHandlers() { grpc_core::MutexLock lock(g_mu.get()); if (!absl::exchange(g_registered, true)) { pthread_atfork(PrepareFork, PostforkParent, PostforkChild); } }; void PrepareFork() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PrepareFork(); } } void PostforkParent() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PostforkParent(); } } void PostforkChild() { grpc_core::MutexLock lock(g_mu.get()); for (auto* forkable : *g_forkables) { forkable->PostforkChild(); } } void ManageForkable(Forkable* forkable) { grpc_core::MutexLock lock(g_mu.get()); g_forkables->insert(forkable); } void StopManagingForkable(Forkable* forkable) { grpc_core::MutexLock lock(g_mu.get()); g_forkables->erase(forkable); } } // namespace experimental } // namespace grpc_event_engine #else // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK namespace grpc_event_engine { namespace experimental { Forkable::Forkable() {} Forkable::~Forkable() {} void RegisterForkHandlers() {} void PrepareFork() {} void PostforkParent() {} void PostforkChild() {} void ManageForkable(Forkable* /* forkable */) {} void StopManagingForkable(Forkable* /* forkable */) {} } // namespace experimental } // namespace grpc_event_engine #endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK <|endoftext|>
<commit_before>#pragma once #ifndef DELEGATE_HPP # define DELEGATE_HPP #include <cassert> #include <bitset> #include <memory> #include <new> #include <type_traits> #include <utility> #include "lightptr.hpp" namespace { template<typename T> constexpr const T &as_const(T &t) { return t; } template <typename T> struct static_allocator { static constexpr ::std::size_t const max_instances = 16; static ::std::bitset<max_instances> memory_map_; static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type store_[max_instances]; }; template <typename T> ::std::bitset<static_allocator<T>::max_instances> static_allocator<T>::memory_map_; template <typename T> typename ::std::aligned_storage<sizeof(T), alignof(T)>::type static_allocator<T>::store_[static_allocator<T>::max_instances]; template <typename T, typename ...A> T* static_new(A&& ...args) { using allocator = static_allocator<T>; ::std::size_t i{}; for (; i != allocator::max_instances; ++i) { if (!as_const(allocator::memory_map_)[i]) { auto p(new (&allocator::store_[i]) T(::std::forward<A>(args)...)); allocator::memory_map_[i] = true; return p; } // else do nothing } assert(0); return nullptr; } template <typename T> void static_delete(T const* const p) { using allocator = static_allocator<T>; auto const i(p - static_cast<T const*>(static_cast<void const*>( allocator::store_))); assert(as_const(allocator::memory_map_)[i]); allocator::memory_map_[i] = false; static_cast<T const*>(static_cast<void const*>( &allocator::store_[i]))->~T(); } } template <typename T> class delegate; template<class R, class ...A> class delegate<R (A...)> { using stub_ptr_type = R (*)(void*, A&&...); delegate(void* const o, stub_ptr_type const m) noexcept : object_ptr_(o), stub_ptr_(m) { } public: delegate() = default; delegate(delegate const&) = default; delegate(delegate&&) = default; delegate(::std::nullptr_t const) noexcept : delegate() { } template <class C> explicit delegate(C const* const o) noexcept : object_ptr_(const_cast<C*>(o)) { } template <class C> explicit delegate(C const& o) noexcept : object_ptr_(const_cast<C*>(&o)) { } delegate(R (* const function_ptr)(A...)) { *this = from(function_ptr); } template <class C> delegate(C* const object_ptr, R (C::* const method_ptr)(A...)) { *this = from(object_ptr, method_ptr); } template <class C> delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const) { *this = from(object_ptr, method_ptr); } template <class C> delegate(C& object, R (C::* const method_ptr)(A...)) { *this = from(object, method_ptr); } template <class C> delegate(C const& object, R (C::* const method_ptr)(A...) const) { *this = from(object, method_ptr); } template < typename T, typename = typename ::std::enable_if< !::std::is_same<delegate, typename ::std::decay<T>::type>{} >::type > delegate(T&& f) { *this = ::std::forward<T>(f); } delegate& operator=(delegate const&) = default; delegate& operator=(delegate&& rhs) = default; delegate& operator=(R (* const rhs)(A...)) { return *this = from(rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...)) { return *this = from(static_cast<C*>(object_ptr_), rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...) const) { return *this = from(static_cast<C const*>(object_ptr_), rhs); } template < typename T, typename = typename ::std::enable_if< !::std::is_same<delegate, typename ::std::decay<T>::type>{} >::type > delegate& operator=(T&& f) { using functor_type = typename ::std::decay<T>::type; store_.reset(static_new<functor_type>(::std::forward<T>(f)), functor_deleter<functor_type>); object_ptr_ = store_.get(); stub_ptr_ = functor_stub<functor_type>; deleter_ = deleter_stub<functor_type>; return *this; } template <R (* const function_ptr)(A...)> static delegate from() noexcept { return { nullptr, function_stub<function_ptr> }; } template <class C, R (C::* const method_ptr)(A...)> static delegate from(C* const object_ptr) noexcept { return { object_ptr, method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...) const> static delegate from(C const* const object_ptr) noexcept { return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...)> static delegate from(C& object) noexcept { return { &object, method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...) const> static delegate from(C const& object) noexcept { return { const_cast<C*>(&object), const_method_stub<C, method_ptr> }; } template <typename T> static delegate from(T&& f) { return ::std::forward<T>(f); } static delegate from(R (* const function_ptr)(A...)) { return [function_ptr](A&&... args) { return (*function_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C* const object_ptr, R (C::* const method_ptr)(A...)) { return [object_ptr, method_ptr](A&&... args) { return (object_ptr->*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C const* const object_ptr, R (C::* const method_ptr)(A...) const) { return [object_ptr, method_ptr](A&&... args) { return (object_ptr->*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C& object, R (C::* const method_ptr)(A...)) { return [&object, method_ptr](A&&... args) { return (object.*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C const& object, R (C::* const method_ptr)(A...) const) { return [&object, method_ptr](A&&... args) { return (object.*method_ptr)(::std::forward<A>(args)...); }; } void reset() { stub_ptr_ = nullptr; store_.reset(); } void reset_stub() noexcept { stub_ptr_ = nullptr; } void swap(delegate& other) noexcept { ::std::swap(*this, other); } bool operator==(delegate const& rhs) const noexcept { return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_); } bool operator!=(delegate const& rhs) const noexcept { return !operator==(rhs); } bool operator<(delegate const& rhs) const noexcept { return (object_ptr_ < rhs.object_ptr_) || ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_)); } bool operator==(::std::nullptr_t const) const noexcept { return !stub_ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return stub_ptr_; } explicit operator bool() const noexcept { return stub_ptr_; } R operator()(A... args) const { // assert(stub_ptr); return stub_ptr_(object_ptr_, ::std::forward<A>(args)...); } private: friend class ::std::hash<delegate>; using deleter_type = void (*)(void const*); void* object_ptr_; stub_ptr_type stub_ptr_{}; deleter_type deleter_; light_ptr<void> store_; template <class T> static void functor_deleter(void* const p) { static_cast<T const*>(p)->~T(); static_delete(static_cast<T const*>(p)); } template <class T> static void deleter_stub(void const* const p) { static_cast<T const*>(p)->~T(); } template <R (*function_ptr)(A...)> static R function_stub(void* const, A&&... args) { return function_ptr(::std::forward<A>(args)...); } template <class C, R (C::*method_ptr)(A...)> static R method_stub(void* const object_ptr, A&&... args) { return (static_cast<C*>(object_ptr)->*method_ptr)( ::std::forward<A>(args)...); } template <class C, R (C::*method_ptr)(A...) const> static R const_method_stub(void* const object_ptr, A&&... args) { return (static_cast<C const*>(object_ptr)->*method_ptr)( ::std::forward<A>(args)...); } template <typename T> static R functor_stub(void* const object_ptr, A&&... args) { return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...); } }; namespace std { template <typename R, typename ...A> struct hash<delegate<R (A...)> > { size_t operator()(delegate<R (A...)> const& d) const noexcept { auto const seed(hash<void*>()(d.object_ptr_)); return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }; } #endif // DELEGATE_HPP <commit_msg>strips<commit_after>#pragma once #ifndef DELEGATE_HPP # define DELEGATE_HPP #include <cassert> #include <bitset> #include <memory> #include <new> #include <type_traits> #include <utility> #include "lightptr.hpp" namespace { template<typename T> constexpr const T &as_const(T &t) { return t; } template <typename T> struct static_allocator { static constexpr ::std::size_t const max_instances = 16; static ::std::bitset<max_instances> memory_map_; static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type store_[max_instances]; }; template <typename T> ::std::bitset<static_allocator<T>::max_instances> static_allocator<T>::memory_map_; template <typename T> typename ::std::aligned_storage<sizeof(T), alignof(T)>::type static_allocator<T>::store_[static_allocator<T>::max_instances]; template <typename T, typename ...A> T* static_new(A&& ...args) { using allocator = static_allocator<T>; for (::std::size_t i{}; i != allocator::max_instances; ++i) { if (!as_const(allocator::memory_map_)[i]) { auto p(new (&allocator::store_[i]) T(::std::forward<A>(args)...)); allocator::memory_map_[i] = true; return p; } // else do nothing } assert(0); return nullptr; } template <typename T> void static_delete(T const* const p) { using allocator = static_allocator<T>; auto const i(p - static_cast<T const*>(static_cast<void const*>( allocator::store_))); assert(as_const(allocator::memory_map_)[i]); allocator::memory_map_[i] = false; static_cast<T const*>(static_cast<void const*>( &allocator::store_[i]))->~T(); } } template <typename T> class delegate; template<class R, class ...A> class delegate<R (A...)> { using stub_ptr_type = R (*)(void*, A&&...); delegate(void* const o, stub_ptr_type const m) noexcept : object_ptr_(o), stub_ptr_(m) { } public: delegate() = default; delegate(delegate const&) = default; delegate(delegate&&) = default; delegate(::std::nullptr_t const) noexcept : delegate() { } template <class C> explicit delegate(C const* const o) noexcept : object_ptr_(const_cast<C*>(o)) { } template <class C> explicit delegate(C const& o) noexcept : object_ptr_(const_cast<C*>(&o)) { } delegate(R (* const function_ptr)(A...)) { *this = from(function_ptr); } template <class C> delegate(C* const object_ptr, R (C::* const method_ptr)(A...)) { *this = from(object_ptr, method_ptr); } template <class C> delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const) { *this = from(object_ptr, method_ptr); } template <class C> delegate(C& object, R (C::* const method_ptr)(A...)) { *this = from(object, method_ptr); } template <class C> delegate(C const& object, R (C::* const method_ptr)(A...) const) { *this = from(object, method_ptr); } template < typename T, typename = typename ::std::enable_if< !::std::is_same<delegate, typename ::std::decay<T>::type>{} >::type > delegate(T&& f) { *this = ::std::forward<T>(f); } delegate& operator=(delegate const&) = default; delegate& operator=(delegate&& rhs) = default; delegate& operator=(R (* const rhs)(A...)) { return *this = from(rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...)) { return *this = from(static_cast<C*>(object_ptr_), rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...) const) { return *this = from(static_cast<C const*>(object_ptr_), rhs); } template < typename T, typename = typename ::std::enable_if< !::std::is_same<delegate, typename ::std::decay<T>::type>{} >::type > delegate& operator=(T&& f) { using functor_type = typename ::std::decay<T>::type; store_.reset(static_new<functor_type>(::std::forward<T>(f)), functor_deleter<functor_type>); object_ptr_ = store_.get(); stub_ptr_ = functor_stub<functor_type>; deleter_ = deleter_stub<functor_type>; return *this; } template <R (* const function_ptr)(A...)> static delegate from() noexcept { return { nullptr, function_stub<function_ptr> }; } template <class C, R (C::* const method_ptr)(A...)> static delegate from(C* const object_ptr) noexcept { return { object_ptr, method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...) const> static delegate from(C const* const object_ptr) noexcept { return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...)> static delegate from(C& object) noexcept { return { &object, method_stub<C, method_ptr> }; } template <class C, R (C::* const method_ptr)(A...) const> static delegate from(C const& object) noexcept { return { const_cast<C*>(&object), const_method_stub<C, method_ptr> }; } template <typename T> static delegate from(T&& f) { return ::std::forward<T>(f); } static delegate from(R (* const function_ptr)(A...)) { return [function_ptr](A&&... args) { return (*function_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C* const object_ptr, R (C::* const method_ptr)(A...)) { return [object_ptr, method_ptr](A&&... args) { return (object_ptr->*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C const* const object_ptr, R (C::* const method_ptr)(A...) const) { return [object_ptr, method_ptr](A&&... args) { return (object_ptr->*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C& object, R (C::* const method_ptr)(A...)) { return [&object, method_ptr](A&&... args) { return (object.*method_ptr)(::std::forward<A>(args)...); }; } template <class C> static delegate from(C const& object, R (C::* const method_ptr)(A...) const) { return [&object, method_ptr](A&&... args) { return (object.*method_ptr)(::std::forward<A>(args)...); }; } void reset() { stub_ptr_ = nullptr; store_.reset(); } void reset_stub() noexcept { stub_ptr_ = nullptr; } void swap(delegate& other) noexcept { ::std::swap(*this, other); } bool operator==(delegate const& rhs) const noexcept { return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_); } bool operator!=(delegate const& rhs) const noexcept { return !operator==(rhs); } bool operator<(delegate const& rhs) const noexcept { return (object_ptr_ < rhs.object_ptr_) || ((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_)); } bool operator==(::std::nullptr_t const) const noexcept { return !stub_ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return stub_ptr_; } explicit operator bool() const noexcept { return stub_ptr_; } R operator()(A... args) const { // assert(stub_ptr); return stub_ptr_(object_ptr_, ::std::forward<A>(args)...); } private: friend class ::std::hash<delegate>; using deleter_type = void (*)(void const*); void* object_ptr_; stub_ptr_type stub_ptr_{}; deleter_type deleter_; light_ptr<void> store_; template <class T> static void functor_deleter(void* const p) { static_cast<T const*>(p)->~T(); static_delete(static_cast<T const*>(p)); } template <class T> static void deleter_stub(void const* const p) { static_cast<T const*>(p)->~T(); } template <R (*function_ptr)(A...)> static R function_stub(void* const, A&&... args) { return function_ptr(::std::forward<A>(args)...); } template <class C, R (C::*method_ptr)(A...)> static R method_stub(void* const object_ptr, A&&... args) { return (static_cast<C*>(object_ptr)->*method_ptr)( ::std::forward<A>(args)...); } template <class C, R (C::*method_ptr)(A...) const> static R const_method_stub(void* const object_ptr, A&&... args) { return (static_cast<C const*>(object_ptr)->*method_ptr)( ::std::forward<A>(args)...); } template <typename T> static R functor_stub(void* const object_ptr, A&&... args) { return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...); } }; namespace std { template <typename R, typename ...A> struct hash<delegate<R (A...)> > { size_t operator()(delegate<R (A...)> const& d) const noexcept { auto const seed(hash<void*>()(d.object_ptr_)); return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }; } #endif // DELEGATE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2017 Vittorio Romeo // MIT License | https://opensource.org/licenses/MIT // http://vittorioromeo.info | [email protected] #pragma once #include "../meta/forward_like.hpp" #include "../meta/replace_all.hpp" #include "../meta/y_combinator.hpp" #include "../utils/fwd.hpp" #include "../utils/returns.hpp" #include "../utils/overload.hpp" #include "../visitation/visit.hpp" #include "./visit.hpp" #include "./match.hpp" #include "./original_type.hpp" #include "../traits/adt/is_visitable.hpp" #include "../traits/adt/alternatives.hpp" #include <type_traits> namespace scelta::experimental::recursive { namespace impl { struct deduce_rt{}; /* template <typename F> struct bco_adapter : F { template <typename FFwd> constexpr bco_adapter(FFwd&& f) noexcept(noexcept(F(FWD(f)))) : F(FWD(f)) { } template <typename T, typename... Ts> constexpr auto operator()(T&&, Ts&&... xs) { } }; */ template <typename T> using original_decay_t = ::scelta::recursive::impl::original_type_t<std::decay_t<T>>; template <typename T> using original_decay_first_alternative_t = ::scelta::traits::adt::first_alternative<original_decay_t<T>>; template <typename T> struct tw { using type = T ; }; template <typename... Fs> constexpr auto make_recursive_visitor_2(Fs&&... fs) { // clang-format off return [o = overload(FWD(fs)...)](auto t) mutable { using Return = typename decltype(t)::type; return meta::y_combinator( // Recurse on this lambda via Y combinator to pass it back // as part of the bound `recurse` argument. [o = std::move(o)](auto self, auto&&... xs) mutable -> Return { // Invoke the overload... return o( // Passing a visitor that invokes `self` to the // `recurse` argument. [&self](auto&&... vs) -> Return { return ::scelta::recursive::visit<Return>( self, FWD(vs)...); }, // Forwarding the rest of the arguments. FWD(xs)...); } ); }; // clang-format on } template <typename Return, typename BCO> struct with_bound_base_cases : private BCO // "base case overload", EBO { template <typename BCOFwd> constexpr with_bound_base_cases(BCOFwd&& bco) noexcept( noexcept(BCO(FWD(bco)))) : BCO(FWD(bco)) { } template <typename... RecursiveCases> constexpr auto operator()(RecursiveCases&&... rcs) { constexpr bool has_recursive_cases = (::scelta::traits::adt::is_visitable_v<RecursiveCases&&> && ...); if constexpr(!has_recursive_cases) { // base case overload with one extra argument (+1 arity) auto adapted_bco = [bco = static_cast<BCO&&>(*this)] (auto, auto&&... xs) mutable SCELTA_NOEXCEPT_AND_TRT(std::declval<BCO&&>()(FWD(xs)...)) { return bco(FWD(xs)...); }; return [rv = make_recursive_visitor_2( // unresolved recursive visitor std::move(adapted_bco), FWD(rcs)... )](auto&&... vs) mutable { using rt = std::conditional_t< std::is_same_v<Return, deduce_rt>, // result of calling BCO& (unadapted overload) with the first alternative of each variant std::result_of_t<BCO&(original_decay_first_alternative_t<decltype(vs)>...)>, //decltype(std::declval<BCO&>()(std::declval<original_decay_first_alternative_t<decltype(vs)>>()...)), // user-specified result Return >; auto resolved_vis = rv(tw<rt>{}); return ::scelta::recursive::visit<rt>(resolved_vis, FWD(vs)...); }; } else { return ::scelta::visit(static_cast<BCO&>(*this), FWD(rcs)...); } } }; // clang-format off template <typename Return, typename... Fs> constexpr auto make_bound_base_cases(Fs&&... fs) SCELTA_RETURNS( with_bound_base_cases< Return, std::decay_t<decltype(::scelta::overload(FWD(fs)...))> >{::scelta::overload(FWD(fs)...)} ) // clang-format on } // First `match` invocation takes one or more base cases. // Second invocation takes zero or more recursive cases. // Return type can be optionally specified explicitly (deduced by default). // clang-format off template <typename Return = impl::deduce_rt, typename... BaseCases> constexpr auto match(BaseCases&&... bcs) SCELTA_RETURNS( impl::make_bound_base_cases<Return>(FWD(bcs)...) ) // clang-format on } // TODO: complete <commit_msg>cleanup<commit_after>// Copyright (c) 2017 Vittorio Romeo // MIT License | https://opensource.org/licenses/MIT // http://vittorioromeo.info | [email protected] #pragma once #include "../meta/forward_like.hpp" #include "../meta/replace_all.hpp" #include "../meta/y_combinator.hpp" #include "../utils/fwd.hpp" #include "../utils/returns.hpp" #include "../utils/overload.hpp" #include "../visitation/visit.hpp" #include "./visit.hpp" #include "./match.hpp" #include "./original_type.hpp" #include "../traits/adt/is_visitable.hpp" #include "../traits/adt/alternatives.hpp" #include <type_traits> namespace scelta::experimental::recursive { namespace impl { // Tag type that when passed to `match` attempts to deduce the return // type by invoking the base case overload set with the first // alternative of the visitable. struct deduce_rt { }; template <typename T> using original_decay_t = ::scelta::recursive::impl::original_type_t<std::decay_t<T>>; template <typename T> using original_decay_first_alternative_t = ::scelta::traits::adt::first_alternative<original_decay_t<T>>; template <typename BCO> // TODO: this is not really a bco, it's an overload of everything struct unresolved_visitor : BCO { template <typename BCOFwd> constexpr unresolved_visitor(BCOFwd&& bco) noexcept(noexcept(BCO{FWD(bco)})) : BCO{FWD(bco)} { } template <typename Return> constexpr auto resolve() & { // clang-format off return meta::y_combinator( // Recurse on this lambda via Y combinator to pass it back // as part of the bound `recurse` argument. [this](auto self, auto&&... xs) mutable->Return { // TODO: does `this` live long enough? // Invoke the overload... return static_cast<BCO&>(*this)( // Passing a visitor that invokes `self` to the // `recurse` argument. [&self](auto&&... vs) -> Return { return ::scelta::recursive::visit<Return>( self, FWD(vs)...); }, // Forwarding the rest of the arguments. FWD(xs)...); }); // clang-format on } }; template <typename BCO> constexpr auto make_unresolved_visitor(BCO&& bco) SCELTA_RETURNS( unresolved_visitor<std::decay_t<BCO>>{FWD(bco)} ) template <typename Return, typename BCO> struct with_bound_base_cases : private BCO // "base case overload", EBO { template <typename BCOFwd> constexpr with_bound_base_cases(BCOFwd&& bco) noexcept( noexcept(BCO(FWD(bco)))) : BCO(FWD(bco)) { } template <typename... RecursiveCases> constexpr auto operator()(RecursiveCases&&... rcs) { constexpr bool has_recursive_cases = !(::scelta::traits::adt::is_visitable_v<RecursiveCases&&> && ...); if constexpr(has_recursive_cases) { // base case overload with one extra argument (+1 arity) auto adapted_bco = [bco = static_cast<BCO&&>(*this)] (auto, auto&&... xs) mutable SCELTA_NOEXCEPT_AND_TRT(std::declval<BCO&&>()(FWD(xs)...)) { return bco(FWD(xs)...); }; auto o = overload(std::move(adapted_bco), FWD(rcs)...); return [rv = make_unresolved_visitor(std::move(o))](auto&&... vs) mutable { using rt = std::conditional_t< std::is_same_v<Return, deduce_rt>, // result of calling BCO& (unadapted overload) with the first alternative of each variant std::result_of_t<BCO&(original_decay_first_alternative_t<decltype(vs)>...)>, // user-specified return type Return >; auto resolved_vis = rv.template resolve<rt>(); return ::scelta::recursive::visit<rt>(resolved_vis, FWD(vs)...); }; } else { return ::scelta::visit(static_cast<BCO&>(*this), FWD(rcs)...); } } }; // clang-format off template <typename Return, typename... Fs> constexpr auto make_bound_base_cases(Fs&&... fs) SCELTA_RETURNS( with_bound_base_cases< Return, std::decay_t<decltype(::scelta::overload(FWD(fs)...))> >{::scelta::overload(FWD(fs)...)} ) // clang-format on } // First `match` invocation takes one or more base cases. // Second invocation takes zero or more recursive cases. // Return type can be optionally specified explicitly (deduced by default). // clang-format off template <typename Return = impl::deduce_rt, typename... BaseCases> constexpr auto match(BaseCases&&... bcs) SCELTA_RETURNS( impl::make_bound_base_cases<Return>(FWD(bcs)...) ) // clang-format on } // TODO: complete <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <ctime> #include <cstdio> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" //#include "opencv2/nonfree/nonfree.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; using namespace std; Mat frame,img,ROI; Rect cropRect(0,0,0,0); Point P1(0,0); Point P2(0,0); const char* winName="Crop Image"; bool clicked=false; int i=0; char imgName[15]; void checkBoundary(){ //check croping rectangle exceed image boundary if(cropRect.width>img.cols-cropRect.x) cropRect.width=img.cols-cropRect.x; if(cropRect.height>img.rows-cropRect.y) cropRect.height=img.rows-cropRect.y; if(cropRect.x<0) cropRect.x=0; if(cropRect.y<0) cropRect.height=0; } void showImage(){ img=frame.clone(); checkBoundary(); if(cropRect.width>0&&cropRect.height>0){ ROI=frame(cropRect); imshow("cropped",ROI); } rectangle(img, cropRect, Scalar(0,255,0), 1, 8, 0 ); imshow(winName,img); } void onMouse( int event, int x, int y, int f, void* ){ switch(event){ case CV_EVENT_LBUTTONDOWN : clicked=true; P1.x=x; P1.y=y; P2.x=x; P2.y=y; break; case CV_EVENT_LBUTTONUP : P2.x=x; P2.y=y; clicked=false; break; case CV_EVENT_MOUSEMOVE : if(clicked){ P2.x=x; P2.y=y; } break; default : break; } if(clicked){ if(P1.x>P2.x){ cropRect.x=P2.x; cropRect.width=P1.x-P2.x; } else { cropRect.x=P1.x; cropRect.width=P2.x-P1.x; } if(P1.y>P2.y){ cropRect.y=P2.y; cropRect.height=P1.y-P2.y; } else { cropRect.y=P1.y; cropRect.height=P2.y-P1.y; } } showImage(); } int main( int argc, char** argv ) { if (argc != 1) return -1; CvCapture* capture; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected! "); return -1; } namedWindow(winName, CV_WINDOW_AUTOSIZE); // Mat frame; while (true) { frame = cvQueryFrame(capture); if (frame.empty()) { printf("No captured frame -- Break!"); break; } imshow( winName, frame); char input = waitKey(10); if (input == 's') { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer, 80, "%Y-%m-%d", timeinfo); std::puts(buffer); std::string str(buffer); cout<<"Click and drag for Selection"<<endl<<endl; cout<<"------> Press 's' to save"<<endl<<endl; cout<<"------> Press '8' to move up"<<endl; cout<<"------> Press '2' to move down"<<endl; cout<<"------> Press '6' to move right"<<endl; cout<<"------> Press '4' to move left"<<endl<<endl; cout<<"------> Press 'w' increas top"<<endl; cout<<"------> Press 'x' increas bottom"<<endl; cout<<"------> Press 'd' increas right"<<endl; cout<<"------> Press 'a' increas left"<<endl<<endl; cout<<"------> Press 't' decrease top"<<endl; cout<<"------> Press 'b' decrease bottom"<<endl; cout<<"------> Press 'h' decrease right"<<endl; cout<<"------> Press 'f' decrease left"<<endl<<endl; cout<<"------> Press 'r' to reset"<<endl; cout<<"------> Press 'Esc' to quit"<<endl<<endl; // src=imread("src.png",1); setMouseCallback(winName,onMouse,NULL ); imshow(winName,frame); while(1){ char c=waitKey(); if(c=='s'&&ROI.data) { sprintf(imgName,"%d.jpg",i++); imwrite(imgName,ROI); cout<<" Saved "<<imgName<<endl; } if(c=='6') cropRect.x++; if(c=='4') cropRect.x--; if(c=='8') cropRect.y--; if(c=='2') cropRect.y++; if(c=='w') { cropRect.y--; cropRect.height++;} if(c=='d') cropRect.width++; if(c=='x') cropRect.height++; if(c=='a') { cropRect.x--; cropRect.width++;} if(c=='t') { cropRect.y++; cropRect.height--;} if(c=='h') cropRect.width--; if(c=='b') cropRect.height--; if(c=='f') { cropRect.x++; cropRect.width--;} if(c==27) break; if(c=='r') {cropRect.x=0;cropRect.y=0;cropRect.width=0;cropRect.height=0;} showImage(); } } } //imwrite("/home/bwi/Desktop/template_" + str + ".jpg", frame); return 0; } <commit_msg>minor<commit_after>#include <stdio.h> #include <iostream> #include <ctime> #include <cstdio> #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" //#include "opencv2/nonfree/nonfree.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; using namespace std; Mat frame,img,ROI; Rect cropRect(0,0,0,0); Point P1(0,0); Point P2(0,0); const char* winName="Crop Image"; bool clicked=false; int i=0; char imgName[15]; void checkBoundary(){ //check croping rectangle exceed image boundary if(cropRect.width>img.cols-cropRect.x) cropRect.width=img.cols-cropRect.x; if(cropRect.height>img.rows-cropRect.y) cropRect.height=img.rows-cropRect.y; if(cropRect.x<0) cropRect.x=0; if(cropRect.y<0) cropRect.height=0; } void showImage(){ img=frame.clone(); checkBoundary(); if(cropRect.width>0&&cropRect.height>0){ ROI=frame(cropRect); imshow("cropped",ROI); } rectangle(img, cropRect, Scalar(0,255,0), 1, 8, 0 ); imshow(winName,img); } void onMouse( int event, int x, int y, int f, void* ){ switch(event){ case CV_EVENT_LBUTTONDOWN : clicked=true; P1.x=x; P1.y=y; P2.x=x; P2.y=y; break; case CV_EVENT_LBUTTONUP : P2.x=x; P2.y=y; clicked=false; break; case CV_EVENT_MOUSEMOVE : if(clicked){ P2.x=x; P2.y=y; } break; default : break; } if(clicked){ if(P1.x>P2.x){ cropRect.x=P2.x; cropRect.width=P1.x-P2.x; } else { cropRect.x=P1.x; cropRect.width=P2.x-P1.x; } if(P1.y>P2.y){ cropRect.y=P2.y; cropRect.height=P1.y-P2.y; } else { cropRect.y=P1.y; cropRect.height=P2.y-P1.y; } } showImage(); } int main( int argc, char** argv ) { if (argc != 1) return -1; CvCapture* capture; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected! "); return -1; } namedWindow(winName, CV_WINDOW_AUTOSIZE); // Mat frame; while (true) { frame = cvQueryFrame(capture); if (frame.empty()) { printf("No captured frame -- Break!"); break; } imshow( winName, frame); char input = waitKey(10); if (input == 's') { std::time_t rawtime; std::tm* timeinfo; char buffer [80]; std::time(&rawtime); timeinfo = std::localtime(&rawtime); std::strftime(buffer, 80, "%Y-%m-%d", timeinfo); std::puts(buffer); std::string str(buffer); cout<<"Click and drag for Selection"<<endl<<endl; cout<<"------> Press 's' to save"<<endl<<endl; cout<<"------> Press '8' to move up"<<endl; cout<<"------> Press '2' to move down"<<endl; cout<<"------> Press '6' to move right"<<endl; cout<<"------> Press '4' to move left"<<endl<<endl; cout<<"------> Press 'w' increas top"<<endl; cout<<"------> Press 'x' increas bottom"<<endl; cout<<"------> Press 'd' increas right"<<endl; cout<<"------> Press 'a' increas left"<<endl<<endl; cout<<"------> Press 't' decrease top"<<endl; cout<<"------> Press 'b' decrease bottom"<<endl; cout<<"------> Press 'h' decrease right"<<endl; cout<<"------> Press 'f' decrease left"<<endl<<endl; cout<<"------> Press 'r' to reset"<<endl; cout<<"------> Press 'Esc' to quit"<<endl<<endl; // src=imread("src.png",1); setMouseCallback(winName,onMouse,NULL ); imshow(winName,frame); while(1){ char c=waitKey(); if(c=='s'&&ROI.data) { //sprintf(imgName,"%d.jpg",i++); //imwrite(imgName,ROI); imwrite("/home/bwi/Desktop/template_" + str + ".jpg", ROI); cout<<" Saved "<<imgName<<endl; break; } if(c=='6') cropRect.x++; if(c=='4') cropRect.x--; if(c=='8') cropRect.y--; if(c=='2') cropRect.y++; if(c=='w') { cropRect.y--; cropRect.height++;} if(c=='d') cropRect.width++; if(c=='x') cropRect.height++; if(c=='a') { cropRect.x--; cropRect.width++;} if(c=='t') { cropRect.y++; cropRect.height--;} if(c=='h') cropRect.width--; if(c=='b') cropRect.height--; if(c=='f') { cropRect.x++; cropRect.width--;} if(c==27) break; if(c=='r') {cropRect.x=0;cropRect.y=0;cropRect.width=0;cropRect.height=0;} showImage(); } } } return 0; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: clang -shared -fPIC -DBUILD_SHARED %s -o%T/libSymbols%shlibext // RUN: %cling --nologo -L%T -lSymbols %s | FileCheck %s // Check that weak symbols do not get re-emitted (ROOT-6124) extern "C" int printf(const char*,...); template <class T> struct StaticStuff { static T s_data; }; template <class T> T StaticStuff<T>::s_data = 42; int compareAddr(int* interp); #ifdef BUILD_SHARED int compareAddr(int* interp) { if (interp != &StaticStuff<int>::s_data) { printf("Wrong address, %ld in shared lib, %ld in interpreter!\n", (long)&StaticStuff<int>::s_data, (long)interp); // CHECK-NOT: Wrong address return 1; } return 0; } #else int Symbols() { return compareAddr(&StaticStuff<int>::s_data); } #endif <commit_msg>Test cannot succeed on Windows due to DLL / dyn linker behavior.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: clang -shared -fPIC -DBUILD_SHARED %s -o%T/libSymbols%shlibext // RUN: %cling --nologo -L%T -lSymbols %s | FileCheck %s // This won't work on Windows as the weak symbol's address is not uniqued // across DLL boundaries. // REQUIRES: not_system-windows // Check that weak symbols do not get re-emitted (ROOT-6124) extern "C" int printf(const char*,...); template <class T> struct StaticStuff { static T s_data; }; template <class T> T StaticStuff<T>::s_data = 42; int compareAddr(int* interp); #ifdef BUILD_SHARED int compareAddr(int* interp) { if (interp != &StaticStuff<int>::s_data) { printf("Wrong address, %ld in shared lib, %ld in interpreter!\n", (long)&StaticStuff<int>::s_data, (long)interp); // CHECK-NOT: Wrong address return 1; } return 0; } #else int Symbols() { return compareAddr(&StaticStuff<int>::s_data); } #endif <|endoftext|>
<commit_before><commit_msg>Fixed test failure after 54314083e16c41082a81520ec44c7aaae44989c7.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_utils.H" #include "fclaw2d_typedefs.h" #include "amr_regrid.H" static void cb_rebuild_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { // Grid doesn't change set_clawpatch(domain,this_patch,this_block_idx,this_patch_idx); // Setup new patch using solver specific routine fclaw2d_solver_functions_t *sf = get_solver_functions(domain); (sf->f_patch_setup)(domain,this_patch,this_block_idx,this_patch_idx); } void rebuild_domain(fclaw2d_domain_t* old_domain, fclaw2d_domain_t* new_domain) { const amr_options_t *gparms = get_domain_parms(old_domain); double t = get_domain_time(old_domain); // Allocate memory for user data types (but they don't get set) init_domain_data(new_domain); copy_domain_data(old_domain,new_domain); // Why isn't this done in copy_domain_data? set_domain_time(new_domain,t); // Allocate memory for new blocks and patches. init_block_and_patch_data(new_domain); // Physical BCs are needed in boundary level exchange // Assume only one block, since we are assuming mthbc int num = new_domain->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &new_domain->blocks[i]; // This is kind of dumb for now, since block won't in general // have the same physical boundary conditions types. set_block_data(block,gparms->mthbc); } fclaw2d_domain_iterate_patches(new_domain, cb_rebuild_patches,(void *) NULL); } static void cb_pack_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_block_t *this_block = &domain->blocks[this_block_idx]; int patch_num = this_block->num_patches_before + this_patch_idx; double* patch_data = (double*) ((void**)user)[patch_num]; pack_clawpatch(this_patch,patch_data); } static void cb_unpack_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_block_t *this_block = &domain->blocks[this_block_idx]; int patch_num = this_block->num_patches_before + this_patch_idx; double* patch_data = (double*) ((void**)user)[patch_num]; unpack_clawpatch(domain,this_patch,this_block_idx,this_patch_idx, patch_data); } void repartition_domain(fclaw2d_domain_t** domain) { // allocate memory for parallel transfor of patches // use data size (in bytes per patch) below. size_t data_size = pack_size(*domain); void ** patch_data = NULL; fclaw2d_domain_allocate_before_partition (*domain, data_size, &patch_data); // For all (patch i) { pack its numerical data into patch_data[i] } fclaw2d_domain_iterate_patches(*domain, cb_pack_patches,(void *) patch_data); // this call creates a new domain that is valid after partitioning // and transfers the data packed above to the new owner processors fclaw2d_domain_t *domain_partitioned = fclaw2d_domain_partition (*domain); fclaw_bool have_new_partition = domain_partitioned != NULL; if (have_new_partition) { rebuild_domain(*domain, domain_partitioned); // update patch array to point to the numerical data that was received fclaw2d_domain_retrieve_after_partition (domain_partitioned,&patch_data); // TODO: for all (patch i) { unpack numerical data from patch_data[i] } fclaw2d_domain_iterate_patches(domain_partitioned, cb_unpack_patches, (void *) patch_data); /* then the old domain is no longer necessary */ amrreset(domain); *domain = domain_partitioned; /* internal clean up */ fclaw2d_domain_complete(*domain); } // free the data that was used in the parallel transfer of patches fclaw2d_domain_free_after_partition (*domain, &patch_data); } #if 0 static void cb_pack_patches_for_ghost_exchange(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_block_t *this_block = &domain->blocks[this_block_idx]; int patch_num = this_block->num_patches_before + this_patch_idx; fclaw2d_patch_t **patch_data = (fclaw2d_patch_t**) &((void*) user)[patch_num]; if (this_patch->flags & FCLAW2D_PATCH_ON_PARALLEL_BOUNDARY) { patch_data = this_patch; /* TODO: put this patch's data location */ } } void setup_parallel_ghost_patches(fclaw2d_domain_t* domain) { size_t data_size = pack_size(domain); void **patch_data, **ghost_data = NULL; /* we just created a grid by init or regrid */ patch_data = P4EST_ALLOC (void *, domain->num_exchange_patches); fclaw2d_domain_iterate_patches(domain, cb_pack_patches_for_ghost_exchange, (void *) patch_data); fclaw2d_domain_allocate_before_exchange (domain, data_size, &ghost_data); fclaw2d_domain_ghost_exchange (domain, data_size, patch_data, ghost_data); // Do time stepping... /* we're about to regrid or terminate the program */ fclaw2d_domain_free_after_exchange (domain, &ghost_data); P4EST_FREE (patch_data); } #endif <commit_msg>Working on parallel ghost exchange<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_forestclaw.H" #include "amr_utils.H" #include "fclaw2d_typedefs.h" #include "amr_regrid.H" static void cb_rebuild_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { // Grid doesn't change set_clawpatch(domain,this_patch,this_block_idx,this_patch_idx); // Setup new patch using solver specific routine fclaw2d_solver_functions_t *sf = get_solver_functions(domain); (sf->f_patch_setup)(domain,this_patch,this_block_idx,this_patch_idx); } void rebuild_domain(fclaw2d_domain_t* old_domain, fclaw2d_domain_t* new_domain) { const amr_options_t *gparms = get_domain_parms(old_domain); double t = get_domain_time(old_domain); // Allocate memory for user data types (but they don't get set) init_domain_data(new_domain); copy_domain_data(old_domain,new_domain); // Why isn't this done in copy_domain_data? set_domain_time(new_domain,t); // Allocate memory for new blocks and patches. init_block_and_patch_data(new_domain); // Physical BCs are needed in boundary level exchange // Assume only one block, since we are assuming mthbc int num = new_domain->num_blocks; for (int i = 0; i < num; i++) { fclaw2d_block_t *block = &new_domain->blocks[i]; // This is kind of dumb for now, since block won't in general // have the same physical boundary conditions types. set_block_data(block,gparms->mthbc); } fclaw2d_domain_iterate_patches(new_domain, cb_rebuild_patches,(void *) NULL); } static void cb_pack_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_block_t *this_block = &domain->blocks[this_block_idx]; int patch_num = this_block->num_patches_before + this_patch_idx; double* patch_data = (double*) ((void**)user)[patch_num]; pack_clawpatch(this_patch,patch_data); } static void cb_unpack_patches(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_block_t *this_block = &domain->blocks[this_block_idx]; int patch_num = this_block->num_patches_before + this_patch_idx; double* patch_data = (double*) ((void**)user)[patch_num]; unpack_clawpatch(domain,this_patch,this_block_idx,this_patch_idx, patch_data); } void repartition_domain(fclaw2d_domain_t** domain) { // allocate memory for parallel transfor of patches // use data size (in bytes per patch) below. size_t data_size = pack_size(*domain); void ** patch_data = NULL; fclaw2d_domain_allocate_before_partition (*domain, data_size, &patch_data); // For all (patch i) { pack its numerical data into patch_data[i] } fclaw2d_domain_iterate_patches(*domain, cb_pack_patches,(void *) patch_data); // this call creates a new domain that is valid after partitioning // and transfers the data packed above to the new owner processors fclaw2d_domain_t *domain_partitioned = fclaw2d_domain_partition (*domain); fclaw_bool have_new_partition = domain_partitioned != NULL; if (have_new_partition) { rebuild_domain(*domain, domain_partitioned); // update patch array to point to the numerical data that was received fclaw2d_domain_retrieve_after_partition (domain_partitioned,&patch_data); // TODO: for all (patch i) { unpack numerical data from patch_data[i] } fclaw2d_domain_iterate_patches(domain_partitioned, cb_unpack_patches, (void *) patch_data); /* then the old domain is no longer necessary */ amrreset(domain); *domain = domain_partitioned; /* internal clean up */ fclaw2d_domain_complete(*domain); } // free the data that was used in the parallel transfer of patches fclaw2d_domain_free_after_partition (*domain, &patch_data); } #if 0 void setup_parallel_ghost_patches(fclaw2d_domain_t* domain) { size_t zz; size_t data_size = pack_size(domain); void **patch_data, **ghost_data = NULL; /* we just created a grid by init or regrid */ patch_data = P4EST_ALLOC (void *, domain->num_exchange_patches); fclaw2d_domain_allocate_before_exchange (domain, data_size, &ghost_data); /* i am assuming that the data that we want to send exists somewhere */ /* you can do this by an iterator instead */ zz = 0; for (nb = 0; nb < domain->num_blocks; ++nb) { for (np = 0; np < domain->blocks[nb].num_patches; ++np) { if (domain->blocks[nb].patches[np].flags & FCLAW2D_PATCH_ON_PARALLEL_BOUNDARY) { fclaw2d_patch_t *this_patch = &domain->blocks[nb].patches[np]; ClawPatch *cp = get_clawpatch(this_patch); double *q = cp->q(); patch_data[zz++] = (void*) q; /* Put this patch's data location */ } } } } fclaw2d_domain_ghost_exchange (domain, data_size, patch_data, ghost_data); // Do time stepping... /* we're about to regrid or terminate the program */ fclaw2d_domain_free_after_exchange (domain, &ghost_data); P4EST_FREE (patch_data); } #endif <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord/util/binarymessagewriter.h> #include <fnord/exception.h> #include <fnord/inspect.h> #include <stdlib.h> #include <string.h> namespace fnord { namespace util { BinaryMessageWriter::BinaryMessageWriter( size_t initial_size) : ptr_(malloc(initial_size)), size_(initial_size), used_(0), owned_(true) { if (ptr_ == nullptr) { RAISE(kMallocError, "malloc() failed"); } } BinaryMessageWriter::BinaryMessageWriter( void* buf, size_t buf_len) : ptr_(buf), size_(buf_len), used_(0), owned_(false) {} BinaryMessageWriter::~BinaryMessageWriter() { if (owned_) { free(ptr_); } } void BinaryMessageWriter::appendUInt8(uint8_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::appendUInt16(uint16_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt16(size_t offset, uint16_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendUInt32(uint32_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt32(size_t offset, uint32_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendUInt64(uint64_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt64(size_t offset, uint64_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendString(const std::string& string) { append(string.data(), string.size()); } void BinaryMessageWriter::appendLenencString(const std::string& string) { appendVarUInt(string.size()); append(string.data(), string.size()); } void BinaryMessageWriter::appendVarUInt(uint64_t value) { unsigned char buf[10]; size_t bytes = 0; do { buf[bytes] = value & 0x7fU; if (value >>= 7) buf[bytes] |= 0x80U; ++bytes; } while (value); append(buf, bytes); } void BinaryMessageWriter::updateString( size_t offset, const std::string& string) { update(offset, string.data(), string.size()); } void* BinaryMessageWriter::data() const { return ptr_; } size_t BinaryMessageWriter::size() const { return used_; } void BinaryMessageWriter::append(void const* data, size_t size) { size_t resize = size_; while (used_ + size > resize) { resize *= 2; } if (resize > size_) { if (!owned_) { RAISE(kBufferOverflowError, "provided buffer is too small"); } auto new_ptr = realloc(ptr_, resize); if (ptr_ == nullptr) { RAISE(kMallocError, "realloc() failed"); } ptr_ = new_ptr; } memcpy(((char*) ptr_) + used_, data, size); used_ += size; } void BinaryMessageWriter::update(size_t offset, void const* data, size_t size) { if (offset + size > size_) { RAISE(kBufferOverflowError, "update exceeds buffer boundary"); } memcpy(((char*) ptr_) + offset, data, size); } void BinaryMessageWriter::clear() { used_ = 0; } template <> void BinaryMessageWriter::appendValue<uint16_t>(const uint16_t& val) { appendUInt16(val); } template <> void BinaryMessageWriter::appendValue<uint32_t>(const uint32_t& val) { appendUInt32(val); } template <> void BinaryMessageWriter::appendValue<String>(const String& val) { appendUInt32(val.size()); append(val.data(), val.size()); } } } <commit_msg>BinaryMessageWriter::appendDouble<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnord/util/binarymessagewriter.h> #include <fnord/exception.h> #include <fnord/IEEE754.h> #include <stdlib.h> #include <string.h> namespace fnord { namespace util { BinaryMessageWriter::BinaryMessageWriter( size_t initial_size) : ptr_(malloc(initial_size)), size_(initial_size), used_(0), owned_(true) { if (ptr_ == nullptr) { RAISE(kMallocError, "malloc() failed"); } } BinaryMessageWriter::BinaryMessageWriter( void* buf, size_t buf_len) : ptr_(buf), size_(buf_len), used_(0), owned_(false) {} BinaryMessageWriter::~BinaryMessageWriter() { if (owned_) { free(ptr_); } } void BinaryMessageWriter::appendUInt8(uint8_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::appendUInt16(uint16_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt16(size_t offset, uint16_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendUInt32(uint32_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt32(size_t offset, uint32_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendUInt64(uint64_t value) { append(&value, sizeof(value)); } void BinaryMessageWriter::updateUInt64(size_t offset, uint64_t value) { update(offset, &value, sizeof(value)); } void BinaryMessageWriter::appendString(const std::string& string) { append(string.data(), string.size()); } void BinaryMessageWriter::appendLenencString(const std::string& string) { appendVarUInt(string.size()); append(string.data(), string.size()); } void BinaryMessageWriter::appendVarUInt(uint64_t value) { unsigned char buf[10]; size_t bytes = 0; do { buf[bytes] = value & 0x7fU; if (value >>= 7) buf[bytes] |= 0x80U; ++bytes; } while (value); append(buf, bytes); } void BinaryMessageWriter::updateString( size_t offset, const std::string& string) { update(offset, string.data(), string.size()); } void BinaryMessageWriter::appendDouble(double value) { auto bytes = IEEE754::toBytes(value); append(&bytes, sizeof(bytes)); } void* BinaryMessageWriter::data() const { return ptr_; } size_t BinaryMessageWriter::size() const { return used_; } void BinaryMessageWriter::append(void const* data, size_t size) { size_t resize = size_; while (used_ + size > resize) { resize *= 2; } if (resize > size_) { if (!owned_) { RAISE(kBufferOverflowError, "provided buffer is too small"); } auto new_ptr = realloc(ptr_, resize); if (ptr_ == nullptr) { RAISE(kMallocError, "realloc() failed"); } ptr_ = new_ptr; } memcpy(((char*) ptr_) + used_, data, size); used_ += size; } void BinaryMessageWriter::update(size_t offset, void const* data, size_t size) { if (offset + size > size_) { RAISE(kBufferOverflowError, "update exceeds buffer boundary"); } memcpy(((char*) ptr_) + offset, data, size); } void BinaryMessageWriter::clear() { used_ = 0; } template <> void BinaryMessageWriter::appendValue<uint16_t>(const uint16_t& val) { appendUInt16(val); } template <> void BinaryMessageWriter::appendValue<uint32_t>(const uint32_t& val) { appendUInt32(val); } template <> void BinaryMessageWriter::appendValue<String>(const String& val) { appendUInt32(val.size()); append(val.data(), val.size()); } } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file utils.H * @brief Defines common fapi2 utilities */ #ifndef FAPI2_UTILS_H_ #define FAPI2_UTILS_H_ #include <stdint.h> #include <return_code.H> #include <target_types.H> #include <plat_utils.H> namespace fapi2 { #ifndef __PPE__ /// /// @brief Enable/Disable special wakeup on processor chip core(s) /// /// Special Wakeup Enable must be done when a HWP is doing an operation that /// requires core(s) to be awake (e.g. modifying the Hcode image). For /// each Special Wakeup Enable call, there must be a subsequent Special Wakeup /// Disable call. /// /// This does not apply to SCOM operations, platforms must handle Special Wakeup /// for SCOM operations internally. /// /// If Special Wakeup is enabled, a core will not go to sleep (if already /// sleeping, it is woken up). If Special Wakeup is disabled, if there are no /// other active Enables, the core is allowed to sleep. /// /// @note Implemented by platform code calling the cpu special wakeup HWP. /// This is a FAPI2 function because each platform may do different things /// Hostboot: Does nothing (cores cannot sleep while Hostboot running) /// FSP: Uses an algorithm to decide when to disable special wakeup /// Cronus: Does Special Wakeup enable/disable as requested /// /// @param[in] i_target /// TARGET_TYPE_PROC_CHIP: Enables/Disables Special Wakeup on all /// cores (EX,EQ chiplets) of the specified chip target. /// TARGET_TYPE_CORE: Enables/Disables Special Wakeup on the /// specified core target (EX,EQ chiplets) /// TARGET_TYPE_EX: Enables/Disables Special Wakeup on the /// specified EX target. /// TARGET_TYPE_EQ: Enables/Disables Special Wakeup on the /// specified EQ target. /// /// @param[in] i_enable true = enable. false = disable. /// /// @return ReturnCode. FAPI2_RC_SUCCESS on success, else platform specified error. /// /// template<TargetType T, typename V> inline ReturnCode specialWakeup(const Target<T, V>& i_target, const bool i_enable) { // enforce the allowed target types static_assert( ((T == fapi2::TARGET_TYPE_PROC_CHIP) || (T == fapi2::TARGET_TYPE_CORE) || (T == fapi2::TARGET_TYPE_EX) || (T == fapi2::TARGET_TYPE_EQ)), "Invalid target type for this function"); ReturnCode l_rc = platSpecialWakeup( i_target, i_enable ); return l_rc; } /// /// @brief Log an error. /// /// @param[in,out] io_rc Reference to ReturnCode (Any references to data and error /// target are removed and rc value is set to success after /// function ends.) /// @param[in] i_sev Fapi error log severity defaulted to unrecoverable /// @param[in] i_unitTestError - flag to log error which does not cause a unit /// test to fail. /// /// @note This function is called from the ffdc collection classes and no longer /// needs to be called directly. /// @note Implemented by platform code /// void logError( fapi2::ReturnCode& io_rc, fapi2::errlSeverity_t i_sev = fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE, bool i_unitTestError = false ); /// /// @brief Create a platform error log /// /// This function will create a platform error log from the passed in /// return code value and will populate the iv_platDataPtr of the return code /// with a pointer to the newly created log. /// /// @param[in,out] io_rc - Reference to ReturnCode /// /// @param[in] i_sev Fapi error log severity defaulted to unrecoverable // // /// @note Implemented by platform code /// void createPlatLog( fapi2::ReturnCode& io_rc, fapi2::errlSeverity_t i_sev = fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE ); #endif // __PPE__ /// /// @brief Delay this thread. Hostboot will use the nanoseconds parameter /// and make a syscall to nanosleep. While in the syscall, the hostboot /// kernel will continue to consume CPU cycles as it looks for a runnable /// task. When the delay time expires, the task becomes runnable and will soon /// return from the syscall. Callers of delay() in the hostboot environment /// will likely have to know the mHz clock speed they are running on and /// compute a non-zero value for i_nanoSeconds. /// /// On the FSP, it was sometimes acceptable to just provide zero for the /// sleep delay time, causing the task to yield its time slice. By the /// time the calling task could run again, it was pretty certain enough /// host cycles had past. This is probably not acceptable in /// the hostboot environment. Callers should calculate and provide a /// sleep value in nanoseconds relative to host clock speed. /// /// On FSP when VBU is the target, then the i_simCycles parameter will be /// used instead. The FSP needs to use the simdispatcher client/server /// API and issue a command to the awan to advance the simulation the /// specified number of cycles. /// /// @param[in] i_nanoSeconds nanoseconds to sleep /// @param[in] i_simCycles count of Awan cycles to advance /// @param[in] i_fixed Determination, for DFT, if this time is /// fixed or not. Defaults to non-fixed /// /// @return ReturnCode. Zero on success, else platform specified error. /// ReturnCode delay(uint64_t i_nanoSeconds, uint64_t i_simCycles, bool i_fixed = false); /// /// @brief Assert a condition, and halt /// /// @param[in] i_expression a boolean representing the assertion /// void Assert(bool i_expression); }; #endif // FAPI2_UTILS_H_ <commit_msg>EKB: HWP Fail Isolation Fapi Hooks<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file utils.H * @brief Defines common fapi2 utilities */ #ifndef FAPI2_UTILS_H_ #define FAPI2_UTILS_H_ #include <stdint.h> #include <return_code.H> #include <target_types.H> #include <plat_utils.H> namespace fapi2 { #ifndef __PPE__ /// /// @brief Enable/Disable special wakeup on processor chip core(s) /// /// Special Wakeup Enable must be done when a HWP is doing an operation that /// requires core(s) to be awake (e.g. modifying the Hcode image). For /// each Special Wakeup Enable call, there must be a subsequent Special Wakeup /// Disable call. /// /// This does not apply to SCOM operations, platforms must handle Special Wakeup /// for SCOM operations internally. /// /// If Special Wakeup is enabled, a core will not go to sleep (if already /// sleeping, it is woken up). If Special Wakeup is disabled, if there are no /// other active Enables, the core is allowed to sleep. /// /// @note Implemented by platform code calling the cpu special wakeup HWP. /// This is a FAPI2 function because each platform may do different things /// Hostboot: Does nothing (cores cannot sleep while Hostboot running) /// FSP: Uses an algorithm to decide when to disable special wakeup /// Cronus: Does Special Wakeup enable/disable as requested /// /// @param[in] i_target /// TARGET_TYPE_PROC_CHIP: Enables/Disables Special Wakeup on all /// cores (EX,EQ chiplets) of the specified chip target. /// TARGET_TYPE_CORE: Enables/Disables Special Wakeup on the /// specified core target (EX,EQ chiplets) /// TARGET_TYPE_EX: Enables/Disables Special Wakeup on the /// specified EX target. /// TARGET_TYPE_EQ: Enables/Disables Special Wakeup on the /// specified EQ target. /// /// @param[in] i_enable true = enable. false = disable. /// /// @return ReturnCode. FAPI2_RC_SUCCESS on success, else platform specified error. /// /// template<TargetType T, typename V> inline ReturnCode specialWakeup(const Target<T, V>& i_target, const bool i_enable) { // enforce the allowed target types static_assert( ((T == fapi2::TARGET_TYPE_PROC_CHIP) || (T == fapi2::TARGET_TYPE_CORE) || (T == fapi2::TARGET_TYPE_EX) || (T == fapi2::TARGET_TYPE_EQ)), "Invalid target type for this function"); ReturnCode l_rc = platSpecialWakeup( i_target, i_enable ); return l_rc; } /// /// @brief Log an error. /// /// @param[in,out] io_rc Reference to ReturnCode (Any references to data and error /// target are removed and rc value is set to success after /// function ends.) /// @param[in] i_sev Fapi error log severity defaulted to unrecoverable /// @param[in] i_unitTestError - flag to log error which does not cause a unit /// test to fail. /// /// @note This function is called from the ffdc collection classes and no longer /// needs to be called directly. /// @note Implemented by platform code /// void logError( fapi2::ReturnCode& io_rc, fapi2::errlSeverity_t i_sev = fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE, bool i_unitTestError = false ); /// /// @brief Create a platform error log /// /// This function will create a platform error log from the passed in /// return code value and will populate the iv_platDataPtr of the return code /// with a pointer to the newly created log. /// /// @param[in,out] io_rc - Reference to ReturnCode /// /// @param[in] i_sev Fapi error log severity defaulted to unrecoverable // // /// @note Implemented by platform code /// void createPlatLog( fapi2::ReturnCode& io_rc, fapi2::errlSeverity_t i_sev = fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE ); /// /// @brief Associate an error to PRD PLID /// /// @param[in] i_target Reference to target /// @param[in,out] io_rc Reference to ReturnCode /// @param[in] i_sev Fapi error log severity defaulted to unrecoverable /// @param[in] i_unitTestError - flag to log error which does not cause a unit /// test to fail. /// /// @note Implemented by platform code /// void log_related_error( const Target<TARGET_TYPE_ALL>& i_target, fapi2::ReturnCode& io_rc, const fapi2::errlSeverity_t i_sev = fapi2::FAPI2_ERRL_SEV_UNRECOVERABLE, const bool i_unitTestError = false ); #endif // __PPE__ /// /// @brief Delay this thread. Hostboot will use the nanoseconds parameter /// and make a syscall to nanosleep. While in the syscall, the hostboot /// kernel will continue to consume CPU cycles as it looks for a runnable /// task. When the delay time expires, the task becomes runnable and will soon /// return from the syscall. Callers of delay() in the hostboot environment /// will likely have to know the mHz clock speed they are running on and /// compute a non-zero value for i_nanoSeconds. /// /// On the FSP, it was sometimes acceptable to just provide zero for the /// sleep delay time, causing the task to yield its time slice. By the /// time the calling task could run again, it was pretty certain enough /// host cycles had past. This is probably not acceptable in /// the hostboot environment. Callers should calculate and provide a /// sleep value in nanoseconds relative to host clock speed. /// /// On FSP when VBU is the target, then the i_simCycles parameter will be /// used instead. The FSP needs to use the simdispatcher client/server /// API and issue a command to the awan to advance the simulation the /// specified number of cycles. /// /// @param[in] i_nanoSeconds nanoseconds to sleep /// @param[in] i_simCycles count of Awan cycles to advance /// @param[in] i_fixed Determination, for DFT, if this time is /// fixed or not. Defaults to non-fixed /// /// @return ReturnCode. Zero on success, else platform specified error. /// ReturnCode delay(uint64_t i_nanoSeconds, uint64_t i_simCycles, bool i_fixed = false); /// /// @brief Assert a condition, and halt /// /// @param[in] i_expression a boolean representing the assertion /// void Assert(bool i_expression); }; #endif // FAPI2_UTILS_H_ <|endoftext|>
<commit_before>#include "dynet/nodes.h" #include "dynet/dynet.h" #include "dynet/training.h" #include "dynet/timing.h" #include "dynet/rnn.h" #include "dynet/gru.h" #include "dynet/lstm.h" #include "dynet/fast-lstm.h" #include "dynet/dict.h" #include "dynet/expr.h" #include <sys/stat.h> #include <sys/types.h> #include <iostream> #include <fstream> #include <sstream> #include <type_traits> #include <time.h> #include <boost/serialization/vector.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/program_options.hpp> #include "s2s/encdec.hpp" #include "s2s/decode.hpp" #include "s2s/define.hpp" #include "s2s/comp.hpp" #include "s2s/metrics.hpp" #include "s2s/options.hpp" namespace s2s { void train(const s2s_options &opts){ s2s::dicts dicts; s2s::parallel_corpus para_corp_train; s2s::parallel_corpus para_corp_dev; dicts.set(opts); para_corp_train.load_src(opts.srcfile, dicts); para_corp_train.load_trg(opts.trgfile, dicts); para_corp_train.load_check(); para_corp_dev.load_src(opts.srcvalfile, dicts); para_corp_dev.load_trg(opts.trgvalfile, dicts); para_corp_dev.load_check(); if(opts.guided_alignment == true){ para_corp_train.load_align(opts.alignfile); para_corp_train.load_check_with_align(); para_corp_dev.load_align(opts.alignvalfile); para_corp_dev.load_check_with_align(); } // for debug dicts.save(opts); // for debug dynet::Model model; encoder_decoder* encdec = new encoder_decoder(model, &opts); encdec->enable_dropout(); dynet::Trainer* trainer = nullptr; if(opts.optim == "sgd"){ trainer = new dynet::SimpleSGDTrainer(model); }else if(opts.optim == "momentum_sgd"){ trainer = new dynet::MomentumSGDTrainer(model); }else if(opts.optim == "adagrad"){ trainer = new dynet::AdagradTrainer(model); }else if(opts.optim == "adadelta"){ trainer = new dynet::AdadeltaTrainer(model); }else if(opts.optim == "adam"){ trainer = new dynet::AdamTrainer(model); }else{ std::cerr << "Trainer does not exist !"<< std::endl; assert(false); } float learning_rate = opts.learning_rate; trainer->eta0 = learning_rate; trainer->eta = learning_rate; trainer->eta_decay = 0.f; trainer->clip_threshold = opts.clip_threshold; trainer->clipping_enabled = opts.clipping_enabled; unsigned int epoch = 0; float align_w = opts.guided_alignment_weight; while(epoch < opts.epochs){ // train para_corp_train.shuffle(); batch one_batch; unsigned int bid = 0; while(para_corp_train.next_batch_para(one_batch, opts.max_batch_train, dicts)){ bid++; auto chrono_start = std::chrono::system_clock::now(); dynet::ComputationGraph cg; std::vector<dynet::expr::Expression> errs_att; std::vector<dynet::expr::Expression> errs_out; float loss_att = 0.0; float loss_out = 0.0; std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg); std::vector<dynet::expr::Expression> i_feed = encdec->init_feed(one_batch, cg); for (unsigned int t = 0; t < one_batch.trg.size() - 1; ++t) { dynet::expr::Expression i_att_t = encdec->decoder_attention(cg, one_batch.trg[t], i_feed[t], i_enc[0]); if(opts.guided_alignment == true){ for(unsigned int i = 0; i < one_batch.align.at(t).size(); i++){ assert(0 <= one_batch.align.at(t).at(i) < one_batch.src.size()); } dynet::expr::Expression i_err = pickneglogsoftmax(i_att_t, one_batch.align.at(t)); errs_att.push_back(i_err); } std::vector<dynet::expr::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]); i_feed.push_back(i_out_t[1]); dynet::expr::Expression i_err = pickneglogsoftmax(i_out_t[0], one_batch.trg[t+1]); errs_out.push_back(i_err); } dynet::expr::Expression i_nerr_out = sum_batches(sum(errs_out)); loss_out = as_scalar(cg.forward(i_nerr_out)); dynet::expr::Expression i_nerr_all; if(opts.guided_alignment == true){ dynet::expr::Expression i_nerr_att = sum_batches(sum(errs_att)); loss_att = as_scalar(cg.incremental_forward(i_nerr_att)); i_nerr_all = i_nerr_out + align_w * i_nerr_att; }else{ i_nerr_all = i_nerr_out; } cg.incremental_forward(i_nerr_all); cg.backward(i_nerr_all); //cg.print_graphviz(); trainer->update(1.0 / double(one_batch.src.at(0).at(0).size())); auto chrono_end = std::chrono::system_clock::now(); auto time_used = (double)std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() / (double)1000; std::cerr << "batch: " << bid; std::cerr << ",\tsize: " << one_batch.src.at(0).at(0).size(); std::cerr << ",\toutput loss: " << loss_out; std::cerr << ",\tattention loss: " << loss_att; std::cerr << ",\tsource length: " << one_batch.src.size(); std::cerr << ",\ttarget length: " << one_batch.trg.size(); std::cerr << ",\ttime: " << time_used << " [s]" << std::endl; std::cerr << "[epoch=" << trainer->epoch << " eta=" << trainer->eta << " align_w=" << align_w << " clips=" << trainer->clips_since_status << " updates=" << trainer->updates_since_status << "] " << std::endl; } para_corp_train.reset_index(); trainer->update_epoch(); trainer->status(); std::cerr << std::endl; // dev encdec->disable_dropout(); std::cerr << "dev" << std::endl; ofstream dev_sents(opts.rootdir + "/dev_" + to_string(epoch) + ".txt"); while(para_corp_dev.next_batch_para(one_batch, opts.max_batch_pred, dicts)){ std::vector<std::vector<unsigned int> > osent; s2s::greedy_decode(one_batch, osent, encdec, dicts, opts); dev_sents << s2s::print_sents(osent, dicts); } dev_sents.close(); para_corp_dev.reset_index(); encdec->enable_dropout(); // save Model ofstream model_out(opts.rootdir + "/" + opts.save_file + "_" + to_string(epoch) + ".model"); boost::archive::text_oarchive model_oa(model_out); model_oa << model << *encdec; model_out.close(); // preparation for next epoch epoch++; if(epoch >= opts.start_epoch){ if(epoch > opts.start_epoch){ if((epoch - opts.start_epoch) % opts.decay_for_each == 0){ learning_rate *= opts.lr_decay; } }else if(epoch == opts.start_epoch){ learning_rate *= opts.lr_decay; } } trainer->eta = learning_rate; if(opts.guided_alignment == true){ if(epoch > opts.guided_alignment_start_epoch){ if((epoch - opts.start_epoch) % opts.guided_alignment_decay_for_each == 0){ align_w *= opts.guided_alignment_decay; } }else if(epoch == opts.start_epoch){ align_w *= opts.guided_alignment_decay; } } } } void predict(const s2s_options &opts){ s2s::dicts dicts; dicts.load(opts); // load model dynet::Model model; encoder_decoder* encdec = new encoder_decoder(model, &opts); //encdec->disable_dropout(); ifstream model_in(opts.modelfile); boost::archive::text_iarchive model_ia(model_in); model_ia >> model >> *encdec; model_in.close(); // predict s2s::monoling_corpus mono_corp; mono_corp.load_src(opts.srcfile, dicts); batch one_batch; ofstream predict_sents(opts.trgfile); encdec->disable_dropout(); while(mono_corp.next_batch_mono(one_batch, opts.max_batch_pred, dicts)){ std::vector<std::vector<unsigned int> > osent; s2s::greedy_decode(one_batch, osent, encdec, dicts, opts); predict_sents << s2s::print_sents(osent, dicts); } predict_sents.close(); } }; int main(int argc, char** argv) { namespace po = boost::program_options; po::options_description bpo("h"); s2s::s2s_options opts; s2s::set_s2s_options(&bpo, &opts); po::variables_map vm; po::store(po::parse_command_line(argc, argv, bpo), vm); po::notify(vm); if(vm.at("mode").as<std::string>() == "train"){ s2s::add_s2s_options_train(&vm, &opts); s2s::check_s2s_options_train(&vm, opts); std::string file_name = opts.rootdir + "/options.txt"; struct stat st; if(stat(opts.rootdir.c_str(), &st) != 0){ mkdir(opts.rootdir.c_str(), 0775); } ofstream out(file_name); boost::archive::text_oarchive oa(out); oa << opts; out.close(); dynet::initialize(argc, argv); s2s::train(opts); }else if(vm.at("mode").as<std::string>() == "predict"){ ifstream in(opts.rootdir + "/options.txt"); boost::archive::text_iarchive ia(in); ia >> opts; in.close(); s2s::check_s2s_options_predict(&vm, opts); dynet::initialize(argc, argv); s2s::predict(opts); }else if(vm.at("mode").as<std::string>() == "test"){ }else{ std::cerr << "Mode does not exist !"<< std::endl; assert(false); } } <commit_msg>guided alignment bug fixed.<commit_after>#include "dynet/nodes.h" #include "dynet/dynet.h" #include "dynet/training.h" #include "dynet/timing.h" #include "dynet/rnn.h" #include "dynet/gru.h" #include "dynet/lstm.h" #include "dynet/fast-lstm.h" #include "dynet/dict.h" #include "dynet/expr.h" #include <sys/stat.h> #include <sys/types.h> #include <iostream> #include <fstream> #include <sstream> #include <type_traits> #include <time.h> #include <boost/serialization/vector.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/program_options.hpp> #include "s2s/encdec.hpp" #include "s2s/decode.hpp" #include "s2s/define.hpp" #include "s2s/comp.hpp" #include "s2s/metrics.hpp" #include "s2s/options.hpp" namespace s2s { void train(const s2s_options &opts){ s2s::dicts dicts; s2s::parallel_corpus para_corp_train; s2s::parallel_corpus para_corp_dev; dicts.set(opts); para_corp_train.load_src(opts.srcfile, dicts); para_corp_train.load_trg(opts.trgfile, dicts); para_corp_train.load_check(); para_corp_dev.load_src(opts.srcvalfile, dicts); para_corp_dev.load_trg(opts.trgvalfile, dicts); para_corp_dev.load_check(); if(opts.guided_alignment == true){ para_corp_train.load_align(opts.alignfile); para_corp_train.load_check_with_align(); para_corp_dev.load_align(opts.alignvalfile); para_corp_dev.load_check_with_align(); } // for debug dicts.save(opts); // for debug dynet::Model model; encoder_decoder* encdec = new encoder_decoder(model, &opts); encdec->enable_dropout(); dynet::Trainer* trainer = nullptr; if(opts.optim == "sgd"){ trainer = new dynet::SimpleSGDTrainer(model); }else if(opts.optim == "momentum_sgd"){ trainer = new dynet::MomentumSGDTrainer(model); }else if(opts.optim == "adagrad"){ trainer = new dynet::AdagradTrainer(model); }else if(opts.optim == "adadelta"){ trainer = new dynet::AdadeltaTrainer(model); }else if(opts.optim == "adam"){ trainer = new dynet::AdamTrainer(model); }else{ std::cerr << "Trainer does not exist !"<< std::endl; assert(false); } float learning_rate = opts.learning_rate; trainer->eta0 = learning_rate; trainer->eta = learning_rate; trainer->eta_decay = 0.f; trainer->clip_threshold = opts.clip_threshold; trainer->clipping_enabled = opts.clipping_enabled; unsigned int epoch = 0; float align_w = opts.guided_alignment_weight; while(epoch < opts.epochs){ // train para_corp_train.shuffle(); batch one_batch; unsigned int bid = 0; while(para_corp_train.next_batch_para(one_batch, opts.max_batch_train, dicts)){ bid++; auto chrono_start = std::chrono::system_clock::now(); dynet::ComputationGraph cg; std::vector<dynet::expr::Expression> errs_att; std::vector<dynet::expr::Expression> errs_out; float loss_att = 0.0; float loss_out = 0.0; std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg); std::vector<dynet::expr::Expression> i_feed = encdec->init_feed(one_batch, cg); for (unsigned int t = 0; t < one_batch.trg.size() - 1; ++t) { dynet::expr::Expression i_att_t = encdec->decoder_attention(cg, one_batch.trg[t], i_feed[t], i_enc[0]); if(opts.guided_alignment == true){ for(unsigned int i = 0; i < one_batch.align.at(t).size(); i++){ assert(0 <= one_batch.align.at(t).at(i) < one_batch.src.size()); } dynet::expr::Expression i_err = pickneglogsoftmax(i_att_t, one_batch.align.at(t)); errs_att.push_back(i_err); } std::vector<dynet::expr::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]); i_feed.push_back(i_out_t[1]); dynet::expr::Expression i_err = pickneglogsoftmax(i_out_t[0], one_batch.trg[t+1]); errs_out.push_back(i_err); } dynet::expr::Expression i_nerr_out = sum_batches(sum(errs_out)); loss_out = as_scalar(cg.forward(i_nerr_out)); dynet::expr::Expression i_nerr_all; if(opts.guided_alignment == true){ dynet::expr::Expression i_nerr_att = sum_batches(sum(errs_att)); loss_att = as_scalar(cg.incremental_forward(i_nerr_att)); i_nerr_all = i_nerr_out + align_w * i_nerr_att; }else{ i_nerr_all = i_nerr_out; } cg.incremental_forward(i_nerr_all); cg.backward(i_nerr_all); //cg.print_graphviz(); trainer->update(1.0 / double(one_batch.src.at(0).at(0).size())); auto chrono_end = std::chrono::system_clock::now(); auto time_used = (double)std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() / (double)1000; std::cerr << "batch: " << bid; std::cerr << ",\tsize: " << one_batch.src.at(0).at(0).size(); std::cerr << ",\toutput loss: " << loss_out; std::cerr << ",\tattention loss: " << loss_att; std::cerr << ",\tsource length: " << one_batch.src.size(); std::cerr << ",\ttarget length: " << one_batch.trg.size(); std::cerr << ",\ttime: " << time_used << " [s]" << std::endl; std::cerr << "[epoch=" << trainer->epoch << " eta=" << trainer->eta << " align_w=" << align_w << " clips=" << trainer->clips_since_status << " updates=" << trainer->updates_since_status << "] " << std::endl; } para_corp_train.reset_index(); trainer->update_epoch(); trainer->status(); std::cerr << std::endl; // dev encdec->disable_dropout(); std::cerr << "dev" << std::endl; ofstream dev_sents(opts.rootdir + "/dev_" + to_string(epoch) + ".txt"); while(para_corp_dev.next_batch_para(one_batch, opts.max_batch_pred, dicts)){ std::vector<std::vector<unsigned int> > osent; s2s::greedy_decode(one_batch, osent, encdec, dicts, opts); dev_sents << s2s::print_sents(osent, dicts); } dev_sents.close(); para_corp_dev.reset_index(); encdec->enable_dropout(); // save Model ofstream model_out(opts.rootdir + "/" + opts.save_file + "_" + to_string(epoch) + ".model"); boost::archive::text_oarchive model_oa(model_out); model_oa << model << *encdec; model_out.close(); // preparation for next epoch epoch++; if(epoch >= opts.start_epoch){ if(epoch > opts.start_epoch){ if((epoch - opts.start_epoch) % opts.decay_for_each == 0){ learning_rate *= opts.lr_decay; } }else if(epoch == opts.start_epoch){ learning_rate *= opts.lr_decay; } } trainer->eta = learning_rate; if(opts.guided_alignment == true){ if(epoch > opts.guided_alignment_start_epoch){ if((epoch - opts.guided_alignment_start_epoch) % opts.guided_alignment_decay_for_each == 0){ align_w *= opts.guided_alignment_decay; } }else if(epoch == opts.guided_alignment_start_epoch){ align_w *= opts.guided_alignment_decay; } } } } void predict(const s2s_options &opts){ s2s::dicts dicts; dicts.load(opts); // load model dynet::Model model; encoder_decoder* encdec = new encoder_decoder(model, &opts); //encdec->disable_dropout(); ifstream model_in(opts.modelfile); boost::archive::text_iarchive model_ia(model_in); model_ia >> model >> *encdec; model_in.close(); // predict s2s::monoling_corpus mono_corp; mono_corp.load_src(opts.srcfile, dicts); batch one_batch; ofstream predict_sents(opts.trgfile); encdec->disable_dropout(); while(mono_corp.next_batch_mono(one_batch, opts.max_batch_pred, dicts)){ std::vector<std::vector<unsigned int> > osent; s2s::greedy_decode(one_batch, osent, encdec, dicts, opts); predict_sents << s2s::print_sents(osent, dicts); } predict_sents.close(); } }; int main(int argc, char** argv) { namespace po = boost::program_options; po::options_description bpo("h"); s2s::s2s_options opts; s2s::set_s2s_options(&bpo, &opts); po::variables_map vm; po::store(po::parse_command_line(argc, argv, bpo), vm); po::notify(vm); if(vm.at("mode").as<std::string>() == "train"){ s2s::add_s2s_options_train(&vm, &opts); s2s::check_s2s_options_train(&vm, opts); std::string file_name = opts.rootdir + "/options.txt"; struct stat st; if(stat(opts.rootdir.c_str(), &st) != 0){ mkdir(opts.rootdir.c_str(), 0775); } ofstream out(file_name); boost::archive::text_oarchive oa(out); oa << opts; out.close(); dynet::initialize(argc, argv); s2s::train(opts); }else if(vm.at("mode").as<std::string>() == "predict"){ ifstream in(opts.rootdir + "/options.txt"); boost::archive::text_iarchive ia(in); ia >> opts; in.close(); s2s::check_s2s_options_predict(&vm, opts); dynet::initialize(argc, argv); s2s::predict(opts); }else if(vm.at("mode").as<std::string>() == "test"){ }else{ std::cerr << "Mode does not exist !"<< std::endl; assert(false); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <vector> #include "util/name_map.h" #include "kernel/free_vars.h" #include "kernel/for_each_fn.h" #include "library/trace.h" #include "library/compiler/rec_fn_macro.h" #include "library/compiler/compiler_step_visitor.h" namespace lean { static expr reduce_arity_of(expr const & e, unsigned i, std::vector<bool> const & keep_bv) { if (i == keep_bv.size()) return e; lean_assert(is_lambda(e)); expr new_body = reduce_arity_of(binding_body(e), i+1, keep_bv); if (keep_bv[i]) return mk_lambda(binding_name(e), binding_domain(e), new_body); else return lower_free_vars(new_body, 1); } /* Auxiliary functor for removing arguments that are not needed in auxiliary function calls */ class remove_args_fn : public compiler_step_visitor { /* Mapping from auxiliary function name to bitvector of used arguments */ name_map<std::vector<bool>> const & m_to_reduce; virtual expr visit_macro(expr const & e) override { /* This module assumes rec_fn_macros have already been eliminated. Remark: the step erase_irrelevant eliminates all occurences. */ lean_assert(!is_rec_fn_macro(e)); return compiler_step_visitor::visit_macro(e); } virtual expr visit_app(expr const & e) override { expr const & fn = get_app_fn(e); if (is_constant(fn)) { if (std::vector<bool> const * bv = m_to_reduce.find(const_name(fn))) { buffer<expr> args; get_app_args(e, args); buffer<expr> new_args; lean_assert(args.size() == bv->size()); for (unsigned i = 0; i < args.size(); i++) { if ((*bv)[i]) new_args.push_back(visit(args[i])); } return mk_app(fn, new_args); } } return compiler_step_visitor::visit_app(e); } public: remove_args_fn(environment const & env, name_map<std::vector<bool>> const & to_reduce): compiler_step_visitor(env), m_to_reduce(to_reduce) {} }; void reduce_arity(environment const & env, buffer<pair<name, expr>> & procs) { lean_assert(!procs.empty()); /* Store in to_reduce a bit-vector indicating which arguments are used by each (auxiliary) function. */ name_map<std::vector<bool>> to_reduce; for (unsigned i = 0; i < procs.size() - 1; i++) { expr fn = procs[i].second; std::vector<bool> keep_bv; bool reduced = false; while (is_lambda(fn)) { expr const & body = binding_body(fn); if (has_free_var(body, 0)) { keep_bv.push_back(true); } else { keep_bv.push_back(false); reduced = true; } fn = body; } if (reduced) { to_reduce.insert(procs[i].first, keep_bv); } } if (to_reduce.empty()) return; /* reduce arity of functions at to_reduce */ for (unsigned i = 0; i < procs.size() - 1; i++) { pair<name, expr> & d = procs[i]; if (std::vector<bool> const * bv = to_reduce.find(d.first)) { d.second = reduce_arity_of(d.second, 0, *bv); } } /* reduce irrelevant application arguments */ remove_args_fn remove_args(env, to_reduce); for (unsigned i = 0; i < procs.size(); i++) { pair<name, expr> & d = procs[i]; d.second = remove_args(d.second); } } } <commit_msg>fix(library/compiler/reduce_arity): incorrect assertion<commit_after>/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <vector> #include "util/name_map.h" #include "kernel/free_vars.h" #include "kernel/for_each_fn.h" #include "library/trace.h" #include "library/compiler/rec_fn_macro.h" #include "library/compiler/compiler_step_visitor.h" namespace lean { static expr reduce_arity_of(expr const & e, unsigned i, std::vector<bool> const & keep_bv) { if (i == keep_bv.size()) return e; lean_assert(is_lambda(e)); expr new_body = reduce_arity_of(binding_body(e), i+1, keep_bv); if (keep_bv[i]) return mk_lambda(binding_name(e), binding_domain(e), new_body); else return lower_free_vars(new_body, 1); } /* Auxiliary functor for removing arguments that are not needed in auxiliary function calls */ class remove_args_fn : public compiler_step_visitor { /* Mapping from auxiliary function name to bitvector of used arguments */ name_map<std::vector<bool>> const & m_to_reduce; virtual expr visit_macro(expr const & e) override { /* This module assumes rec_fn_macros have already been eliminated. Remark: the step erase_irrelevant eliminates all occurences. */ lean_assert(!is_rec_fn_macro(e)); return compiler_step_visitor::visit_macro(e); } virtual expr visit_app(expr const & e) override { expr const & fn = get_app_fn(e); if (is_constant(fn)) { if (std::vector<bool> const * bv = m_to_reduce.find(const_name(fn))) { buffer<expr> args; get_app_args(e, args); buffer<expr> new_args; for (unsigned i = 0; i < args.size(); i++) { /* The case i >= bv->size() can happen when the function is returning a closure. We eta-expand terms, but we may miss cases where the type is opaque (e.g., IO a), or the type is dependent (e.g., T b) where (T is defined as T b := bool.cases_on b nat (nat -> nat)). */ if (i >= bv->size() || (*bv)[i]) new_args.push_back(visit(args[i])); } return mk_app(fn, new_args); } } return compiler_step_visitor::visit_app(e); } public: remove_args_fn(environment const & env, name_map<std::vector<bool>> const & to_reduce): compiler_step_visitor(env), m_to_reduce(to_reduce) {} }; void reduce_arity(environment const & env, buffer<pair<name, expr>> & procs) { lean_assert(!procs.empty()); /* Store in to_reduce a bit-vector indicating which arguments are used by each (auxiliary) function. */ name_map<std::vector<bool>> to_reduce; for (unsigned i = 0; i < procs.size() - 1; i++) { expr fn = procs[i].second; std::vector<bool> keep_bv; bool reduced = false; while (is_lambda(fn)) { expr const & body = binding_body(fn); if (has_free_var(body, 0)) { keep_bv.push_back(true); } else { keep_bv.push_back(false); reduced = true; } fn = body; } if (reduced) { to_reduce.insert(procs[i].first, keep_bv); } } if (to_reduce.empty()) return; /* reduce arity of functions at to_reduce */ for (unsigned i = 0; i < procs.size() - 1; i++) { pair<name, expr> & d = procs[i]; if (std::vector<bool> const * bv = to_reduce.find(d.first)) { d.second = reduce_arity_of(d.second, 0, *bv); } } /* reduce irrelevant application arguments */ remove_args_fn remove_args(env, to_reduce); for (unsigned i = 0; i < procs.size(); i++) { pair<name, expr> & d = procs[i]; d.second = remove_args(d.second); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageAccumulate.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkImageAccumulate.h" #include <math.h> #include <stdlib.h> #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkImageAccumulate* vtkImageAccumulate::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate"); if(ret) { return (vtkImageAccumulate*)ret; } // If the factory was unable to create the object, then create it here. return new vtkImageAccumulate; } //---------------------------------------------------------------------------- // Constructor sets default values vtkImageAccumulate::vtkImageAccumulate() { int idx; for (idx = 0; idx < 3; ++idx) { this->ComponentSpacing[idx] = 1.0; this->ComponentOrigin[idx] = 0.0; this->ComponentExtent[idx*2] = 0; this->ComponentExtent[idx*2+1] = 0; } this->ComponentExtent[1] = 255; } //---------------------------------------------------------------------------- void vtkImageAccumulate::SetComponentExtent(int extent[6]) { int idx, modified = 0; for (idx = 0; idx < 6; ++idx) { if (this->ComponentExtent[idx] != extent[idx]) { this->ComponentExtent[idx] = extent[idx]; this->Modified(); } } if (modified) { this->Modified(); } } //---------------------------------------------------------------------------- void vtkImageAccumulate::SetComponentExtent(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { int extent[6]; extent[0] = minX; extent[1] = maxX; extent[2] = minY; extent[3] = maxY; extent[4] = minZ; extent[5] = maxZ; this->SetComponentExtent(extent); } //---------------------------------------------------------------------------- void vtkImageAccumulate::GetComponentExtent(int extent[6]) { int idx; for (idx = 0; idx < 6; ++idx) { extent[idx] = this->ComponentExtent[idx]; } } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template <class T> static void vtkImageAccumulateExecute(vtkImageAccumulate *self, vtkImageData *inData, T *inPtr, vtkImageData *outData, int *outPtr) { int min0, max0, min1, max1, min2, max2; int idx0, idx1, idx2, idxC; int inInc0, inInc1, inInc2; T *inPtr0, *inPtr1, *inPtr2, *inPtrC; int *outPtrC; int numC, outIdx, *outExtent, *outIncs; float *origin, *spacing; unsigned long count = 0; unsigned long target; self = self; // Zero count in every bin outData->GetExtent(min0, max0, min1, max1, min2, max2); memset((void *)outPtr, 0, (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int)); // Get information to march through data numC = inData->GetNumberOfScalarComponents(); inData->GetExtent(min0, max0, min1, max1, min2, max2); inData->GetIncrements(inInc0, inInc1, inInc2); outExtent = outData->GetExtent(); outIncs = outData->GetIncrements(); origin = outData->GetOrigin(); spacing = outData->GetSpacing(); target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0); target++; inPtr2 = inPtr; for (idx2 = min2; idx2 <= max2; ++idx2) { inPtr1 = inPtr2; for (idx1 = min1; !self->AbortExecute && idx1 <= max1; ++idx1) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0) { inPtrC = inPtr0; // find the bin for this pixel. outPtrC = outPtr; for (idxC = 0; idxC < numC; ++idxC) { // compute the index outIdx = (int)(((float)*inPtrC - origin[idxC]) / spacing[idxC]); if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1]) { // Out of bin range outPtrC = NULL; break; } outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC]; ++inPtrC; } if (outPtrC) { ++(*outPtrC); } inPtr0 += inInc0; } inPtr1 += inInc1; } inPtr2 += inInc2; } } //---------------------------------------------------------------------------- // This method is passed a input and output Data, and executes the filter // algorithm to fill the output from the input. // It just executes a switch statement to call the correct function for // the Datas data types. void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out)) { void *inPtr; void *outPtr; vtkImageData *inData = this->GetInput(); vtkImageData *outData = this->GetOutput(); // We need to allocate our own scalars since we are overriding // the superclasses "Execute()" method. outData->SetExtent(outData->GetWholeExtent()); outData->AllocateScalars(); inPtr = inData->GetScalarPointer(); outPtr = outData->GetScalarPointer(); // Components turned into x, y and z if (this->GetInput()->GetNumberOfScalarComponents() > 3) { vtkErrorMacro("This filter can handle upto 3 components"); return; } // this filter expects that output is type int. if (outData->GetScalarType() != VTK_INT) { vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType() << " must be int\n"); return; } switch (inData->GetScalarType()) { vtkTemplateMacro5(vtkImageAccumulateExecute, this, inData, (VTK_TT *)(inPtr), outData, (int *)(outPtr)); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- void vtkImageAccumulate::ExecuteInformation(vtkImageData *vtkNotUsed(input), vtkImageData *output) { output->SetWholeExtent(this->ComponentExtent); output->SetOrigin(this->ComponentOrigin); output->SetSpacing(this->ComponentSpacing); output->SetNumberOfScalarComponents(1); output->SetScalarType(VTK_INT); } //---------------------------------------------------------------------------- // Get ALL of the input. void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6], int outExt[6]) { int *wholeExtent; outExt = outExt; wholeExtent = this->GetInput()->GetWholeExtent(); memcpy(inExt, wholeExtent, 6*sizeof(int)); } void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent) { vtkImageToImageFilter::PrintSelf(os,indent); os << indent << "ComponentOrigin: ( " << this->ComponentOrigin[0] << ", " << this->ComponentOrigin[1] << ", " << this->ComponentOrigin[2] << " )\n"; os << indent << "ComponentSpacing: ( " << this->ComponentSpacing[0] << ", " << this->ComponentSpacing[1] << ", " << this->ComponentSpacing[2] << " )\n"; } <commit_msg>ERR:Using the wrong input extent<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageAccumulate.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkImageAccumulate.h" #include <math.h> #include <stdlib.h> #include "vtkObjectFactory.h" //---------------------------------------------------------------------------- vtkImageAccumulate* vtkImageAccumulate::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate"); if(ret) { return (vtkImageAccumulate*)ret; } // If the factory was unable to create the object, then create it here. return new vtkImageAccumulate; } //---------------------------------------------------------------------------- // Constructor sets default values vtkImageAccumulate::vtkImageAccumulate() { int idx; for (idx = 0; idx < 3; ++idx) { this->ComponentSpacing[idx] = 1.0; this->ComponentOrigin[idx] = 0.0; this->ComponentExtent[idx*2] = 0; this->ComponentExtent[idx*2+1] = 0; } this->ComponentExtent[1] = 255; } //---------------------------------------------------------------------------- void vtkImageAccumulate::SetComponentExtent(int extent[6]) { int idx, modified = 0; for (idx = 0; idx < 6; ++idx) { if (this->ComponentExtent[idx] != extent[idx]) { this->ComponentExtent[idx] = extent[idx]; this->Modified(); } } if (modified) { this->Modified(); } } //---------------------------------------------------------------------------- void vtkImageAccumulate::SetComponentExtent(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { int extent[6]; extent[0] = minX; extent[1] = maxX; extent[2] = minY; extent[3] = maxY; extent[4] = minZ; extent[5] = maxZ; this->SetComponentExtent(extent); } //---------------------------------------------------------------------------- void vtkImageAccumulate::GetComponentExtent(int extent[6]) { int idx; for (idx = 0; idx < 6; ++idx) { extent[idx] = this->ComponentExtent[idx]; } } //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template <class T> static void vtkImageAccumulateExecute(vtkImageAccumulate *self, vtkImageData *inData, T *inPtr, vtkImageData *outData, int *outPtr) { int min0, max0, min1, max1, min2, max2; int idx0, idx1, idx2, idxC; int inInc0, inInc1, inInc2; T *inPtr0, *inPtr1, *inPtr2, *inPtrC; int *outPtrC; int numC, outIdx, *outExtent, *outIncs; float *origin, *spacing; unsigned long count = 0; unsigned long target; self = self; // Zero count in every bin outData->GetExtent(min0, max0, min1, max1, min2, max2); memset((void *)outPtr, 0, (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int)); // Get information to march through data numC = inData->GetNumberOfScalarComponents(); inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2); inData->GetIncrements(inInc0, inInc1, inInc2); outExtent = outData->GetExtent(); outIncs = outData->GetIncrements(); origin = outData->GetOrigin(); spacing = outData->GetSpacing(); vtkGenericWarningMacro(<<"Executing with: " << min0 << "," << max0 << " " << min1 << "," << max1 << " " << min2 << "," << max2); target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0); target++; inPtr2 = inPtr; for (idx2 = min2; idx2 <= max2; ++idx2) { inPtr1 = inPtr2; for (idx1 = min1; !self->AbortExecute && idx1 <= max1; ++idx1) { if (!(count%target)) { self->UpdateProgress(count/(50.0*target)); } count++; inPtr0 = inPtr1; for (idx0 = min0; idx0 <= max0; ++idx0) { inPtrC = inPtr0; // find the bin for this pixel. outPtrC = outPtr; for (idxC = 0; idxC < numC; ++idxC) { // compute the index outIdx = (int)(((float)*inPtrC - origin[idxC]) / spacing[idxC]); if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1]) { // Out of bin range outPtrC = NULL; break; } outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC]; ++inPtrC; } if (outPtrC) { ++(*outPtrC); } inPtr0 += inInc0; } inPtr1 += inInc1; } inPtr2 += inInc2; } } //---------------------------------------------------------------------------- // This method is passed a input and output Data, and executes the filter // algorithm to fill the output from the input. // It just executes a switch statement to call the correct function for // the Datas data types. void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out)) { void *inPtr; void *outPtr; vtkImageData *inData = this->GetInput(); vtkImageData *outData = this->GetOutput(); vtkDebugMacro(<<"Executing image accumulate"); // We need to allocate our own scalars since we are overriding // the superclasses "Execute()" method. outData->SetExtent(outData->GetWholeExtent()); outData->AllocateScalars(); inPtr = inData->GetScalarPointer(); outPtr = outData->GetScalarPointer(); // Components turned into x, y and z if (this->GetInput()->GetNumberOfScalarComponents() > 3) { vtkErrorMacro("This filter can handle upto 3 components"); return; } // this filter expects that output is type int. if (outData->GetScalarType() != VTK_INT) { vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType() << " must be int\n"); return; } switch (inData->GetScalarType()) { vtkTemplateMacro5(vtkImageAccumulateExecute, this, inData, (VTK_TT *)(inPtr), outData, (int *)(outPtr)); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } //---------------------------------------------------------------------------- void vtkImageAccumulate::ExecuteInformation(vtkImageData *vtkNotUsed(input), vtkImageData *output) { output->SetWholeExtent(this->ComponentExtent); output->SetOrigin(this->ComponentOrigin); output->SetSpacing(this->ComponentSpacing); output->SetNumberOfScalarComponents(1); output->SetScalarType(VTK_INT); } //---------------------------------------------------------------------------- // Get ALL of the input. void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6], int outExt[6]) { int *wholeExtent; outExt = outExt; wholeExtent = this->GetInput()->GetWholeExtent(); memcpy(inExt, wholeExtent, 6*sizeof(int)); } void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent) { vtkImageToImageFilter::PrintSelf(os,indent); os << indent << "ComponentOrigin: ( " << this->ComponentOrigin[0] << ", " << this->ComponentOrigin[1] << ", " << this->ComponentOrigin[2] << " )\n"; os << indent << "ComponentSpacing: ( " << this->ComponentSpacing[0] << ", " << this->ComponentSpacing[1] << ", " << this->ComponentSpacing[2] << " )\n"; os << indent << "ComponentExtent: ( " << this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " " << this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " " << this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n"; } <|endoftext|>
<commit_before>/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * alpaka is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/core/Debug.hpp> #include <type_traits> // std::enable_if #if !defined(__CUDA_ARCH__) #include <boost/core/ignore_unused.hpp> // boost::ignore_unused #endif #include <boost/predef.h> // workarounds //----------------------------------------------------------------------------- //! Disable nvcc warning: //! 'calling a __host__ function from __host__ __device__ function.' //! //! Usage: //! ALPAKA_NO_HOST_ACC_WARNING //! __device__ __host__ function_declaration() //! //! It is not possible to disable the warning for a __host__ function if there are calls of virtual functions inside. //! For this case use a wrapper function. //! WARNING: only use this method if there is no other way to create runnable code. //! Most cases can solved by #ifdef __CUDA_ARCH__ or #ifdef __CUDACC__. //----------------------------------------------------------------------------- #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && defined(__CUDACC__) #if BOOST_COMP_MSVC #define ALPAKA_NO_HOST_ACC_WARNING\ __pragma(hd_warning_disable) #else #define ALPAKA_NO_HOST_ACC_WARNING\ _Pragma("hd_warning_disable") #endif #else #define ALPAKA_NO_HOST_ACC_WARNING #endif //----------------------------------------------------------------------------- //! All functions that can be used on an accelerator have to be attributed with ALPAKA_FN_ACC_CUDA_ONLY or ALPAKA_FN_ACC. //! //! Usage: //! ALPAKA_FN_ACC int add(int a, int b); //----------------------------------------------------------------------------- #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && defined(__CUDACC__) #define ALPAKA_FN_ACC_CUDA_ONLY __device__ __forceinline__ #define ALPAKA_FN_ACC_NO_CUDA __host__ __forceinline__ #define ALPAKA_FN_ACC __device__ __host__ __forceinline__ #define ALPAKA_FN_HOST_ACC __device__ __host__ __forceinline__ #define ALPAKA_FN_HOST __host__ __forceinline__ #else //#define ALPAKA_FN_ACC_CUDA_ONLY inline #define ALPAKA_FN_ACC_NO_CUDA inline #define ALPAKA_FN_ACC inline #define ALPAKA_FN_HOST_ACC inline #define ALPAKA_FN_HOST inline #endif //----------------------------------------------------------------------------- //! Suggests unrolling of the following loop to the compiler. //! //! Usage: //! `ALPAKA_UNROLL //! for(...){...}` // \TODO: Unrolling in non CUDA code? //----------------------------------------------------------------------------- #ifdef __CUDA_ARCH__ #if BOOST_COMP_MSVC #define ALPAKA_UNROLL(...) __pragma(unroll##__VA_ARGS__) #else #define ALPAKA_UNROLL(...) _Pragma("unroll"##__VA_ARGS__) #endif #else #define ALPAKA_UNROLL(...) #endif namespace alpaka { //############################################################################# //! A false_type being dependent on a ignored template parameter. //! This allows to use static_assert in uninstantiated template specializations without triggering. //############################################################################# template< typename T> struct dependent_false_type : std::false_type {}; namespace detail { //############################################################################# //! //############################################################################# template< typename TArg, typename TSfinae = void> struct AssertValueUnsigned; //############################################################################# //! //############################################################################# template< typename TArg> struct AssertValueUnsigned< TArg, typename std::enable_if<!std::is_unsigned<TArg>::value>::type> { ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC static auto assertValueUnsigned( TArg const & arg) -> void { assert(arg >= 0); } }; //############################################################################# //! //############################################################################# template< typename TArg> struct AssertValueUnsigned< TArg, typename std::enable_if<std::is_unsigned<TArg>::value>::type> { ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC static auto assertValueUnsigned( TArg const & arg) -> void { #if !defined(__CUDA_ARCH__) boost::ignore_unused(arg); #endif // Nothing to do for unsigned types. } }; } //----------------------------------------------------------------------------- //! This method checks integral values if they are greater or equal zero. //! The implementation prevents warnings for checking this for unsigned types. //----------------------------------------------------------------------------- template< typename TArg> ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC auto assertValueUnsigned( TArg const & arg) -> void { detail::AssertValueUnsigned< TArg> ::assertValueUnsigned( arg); } } <commit_msg>Fix ALPAKA_UNROLL and add ALPAKA_VECTORIZE<commit_after>/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * alpaka is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/core/Debug.hpp> #include <type_traits> // std::enable_if #if !defined(__CUDA_ARCH__) #include <boost/core/ignore_unused.hpp> // boost::ignore_unused #endif #include <boost/predef.h> // workarounds //----------------------------------------------------------------------------- //! Disable nvcc warning: //! 'calling a __host__ function from __host__ __device__ function.' //! //! Usage: //! ALPAKA_NO_HOST_ACC_WARNING //! __device__ __host__ function_declaration() //! //! It is not possible to disable the warning for a __host__ function if there are calls of virtual functions inside. //! For this case use a wrapper function. //! WARNING: only use this method if there is no other way to create runnable code. //! Most cases can solved by #ifdef __CUDA_ARCH__ or #ifdef __CUDACC__. //----------------------------------------------------------------------------- #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && defined(__CUDACC__) #if BOOST_COMP_MSVC #define ALPAKA_NO_HOST_ACC_WARNING\ __pragma(hd_warning_disable) #else #define ALPAKA_NO_HOST_ACC_WARNING\ _Pragma("hd_warning_disable") #endif #else #define ALPAKA_NO_HOST_ACC_WARNING #endif //----------------------------------------------------------------------------- //! All functions that can be used on an accelerator have to be attributed with ALPAKA_FN_ACC_CUDA_ONLY or ALPAKA_FN_ACC. //! //! Usage: //! ALPAKA_FN_ACC int add(int a, int b); //----------------------------------------------------------------------------- #if defined(ALPAKA_ACC_GPU_CUDA_ENABLED) && defined(__CUDACC__) #define ALPAKA_FN_ACC_CUDA_ONLY __device__ __forceinline__ #define ALPAKA_FN_ACC_NO_CUDA __host__ __forceinline__ #define ALPAKA_FN_ACC __device__ __host__ __forceinline__ #define ALPAKA_FN_HOST_ACC __device__ __host__ __forceinline__ #define ALPAKA_FN_HOST __host__ __forceinline__ #else //#define ALPAKA_FN_ACC_CUDA_ONLY inline #define ALPAKA_FN_ACC_NO_CUDA inline #define ALPAKA_FN_ACC inline #define ALPAKA_FN_HOST_ACC inline #define ALPAKA_FN_HOST inline #endif //----------------------------------------------------------------------------- //! Suggests unrolling of the directly following loop to the compiler. //! //! Usage: //! `ALPAKA_UNROLL //! for(...){...}` // \TODO: Implement for other compilers. //----------------------------------------------------------------------------- #ifdef __CUDA_ARCH__ #if BOOST_COMP_MSVC #define ALPAKA_UNROLL(...) __pragma(unroll __VA_ARGS__) #else #define ALPAKA_UNROLL_STRINGIFY(x) #x #define ALPAKA_UNROLL(...) _Pragma(ALPAKA_UNROLL_STRINGIFY(unroll __VA_ARGS__)) #endif #else #if BOOST_COMP_INTEL || BOOST_COMP_IBM || BOOST_COMP_SUNPRO || BOOST_COMP_HPACC #define ALPAKA_UNROLL_STRINGIFY(x) #x #define ALPAKA_UNROLL(...) _Pragma(ALPAKA_UNROLL_STRINGIFY(unroll(__VA_ARGS__))) #elif BOOST_COMP_PGI #define ALPAKA_UNROLL(...) _Pragma("unroll") #else #define ALPAKA_UNROLL(...) #endif #endif //----------------------------------------------------------------------------- //! Suggests vectorization of the directly following loop to the compiler. //! //! Usage: //! `ALPAKA_VECTORIZE //! for(...){...}` // \TODO: Implement for other compilers. // See: http://stackoverflow.com/questions/2706286/pragmas-swp-ivdep-prefetch-support-in-various-compilers //----------------------------------------------------------------------------- #if BOOST_COMP_INTEL || BOOST_COMP_HPACC #define ALPAKA_VECTORIZE(...) _Pragma("ivdep") #elif BOOST_COMP_PGI #define ALPAKA_VECTORIZE(...) _Pragma("vector") #elif BOOST_COMP_MSVC #define ALPAKA_VECTORIZE(...) __pragma(loop(ivdep)) #else #define ALPAKA_VECTORIZE(...) #endif namespace alpaka { //############################################################################# //! A false_type being dependent on a ignored template parameter. //! This allows to use static_assert in uninstantiated template specializations without triggering. //############################################################################# template< typename T> struct dependent_false_type : std::false_type {}; namespace detail { //############################################################################# //! //############################################################################# template< typename TArg, typename TSfinae = void> struct AssertValueUnsigned; //############################################################################# //! //############################################################################# template< typename TArg> struct AssertValueUnsigned< TArg, typename std::enable_if<!std::is_unsigned<TArg>::value>::type> { ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC static auto assertValueUnsigned( TArg const & arg) -> void { assert(arg >= 0); } }; //############################################################################# //! //############################################################################# template< typename TArg> struct AssertValueUnsigned< TArg, typename std::enable_if<std::is_unsigned<TArg>::value>::type> { ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC static auto assertValueUnsigned( TArg const & arg) -> void { #if !defined(__CUDA_ARCH__) boost::ignore_unused(arg); #endif // Nothing to do for unsigned types. } }; } //----------------------------------------------------------------------------- //! This method checks integral values if they are greater or equal zero. //! The implementation prevents warnings for checking this for unsigned types. //----------------------------------------------------------------------------- template< typename TArg> ALPAKA_NO_HOST_ACC_WARNING ALPAKA_FN_HOST_ACC auto assertValueUnsigned( TArg const & arg) -> void { detail::AssertValueUnsigned< TArg> ::assertValueUnsigned( arg); } } <|endoftext|>
<commit_before>/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * alpaka is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/vec/Vec.hpp> // Vec #include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC #if !defined(__CUDA_ARCH__) #include <boost/core/ignore_unused.hpp> // boost::ignore_unused #endif namespace alpaka { namespace core { namespace detail { //############################################################################# //! Maps a linear index to a N dimensional index. //############################################################################# template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TSfinae = void> struct MapIdx; //############################################################################# //! Maps a 1 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<1u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { #if !defined(__CUDA_ARCH__) boost::ignore_unused(extent); #endif return idx; } }; //############################################################################# //! Maps a 1 dimensional index to a 2 dimensional index. //############################################################################# template<> struct MapIdx< 2u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 2 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<2u>, TElem> const & extent) -> Vec<dim::DimInt<2u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[1u]); return { static_cast<TElem>(idx1d / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 1 dimensional index to a 3 dimensional index. //############################################################################# template<> struct MapIdx< 3u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 3 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<3u>, TElem> const & extent) -> Vec<dim::DimInt<3u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[2]); TElem const xyExtentProd(extent[2u] * extent[1u]); return { static_cast<TElem>(idx1d / xyExtentProd), static_cast<TElem>((idx1d % xyExtentProd) / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 1 dimensional index to a 4 dimensional index. //############################################################################# template<> struct MapIdx< 4u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 4 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<4u>, TElem> const & extent) -> Vec<dim::DimInt<4u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[3]); TElem const xyExtentProd(extent[3u] * extent[2u]); TElem const xyzExtentProd(xyExtentProd * extent[1u]); return { static_cast<TElem>(idx1d / xyzExtentProd), static_cast<TElem>((idx1d % xyzExtentProd) / xyExtentProd), static_cast<TElem>((idx1d % xyExtentProd) / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 2 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 2u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<2u>, TElem> const & idx, Vec<dim::DimInt<2u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { idx[0u] * extent[1u] + idx[1u]}; } }; //############################################################################# //! Maps a 3 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 3u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<3u>, TElem> const & idx, Vec<dim::DimInt<3u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { (idx[0u] * extent[1u] + idx[1u]) * extent[2u] + idx[2u]}; } }; //############################################################################# //! Maps a 4 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 4u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<3u>, TElem> const & idx, Vec<dim::DimInt<3u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { ((idx[0u] * extent[1u] + idx[1u]) * extent[2u] + idx[2u]) * extent[3u] + idx[3u]}; } }; } //############################################################################# //! Maps a N dimensional index to a N dimensional position. //! //! \tparam TidxDimOut Dimension of the index vector to map to. //! \tparam TidxDimIn Dimension of the index vector to map from. //! \tparam TElem Type of the elements of the index vector to map from. //############################################################################# ALPAKA_NO_HOST_ACC_WARNING template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TElem> ALPAKA_FN_HOST_ACC auto mapIdx( Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent) -> Vec<dim::DimInt<TidxDimOut>, TElem> { return detail::MapIdx< TidxDimOut, TidxDimIn> ::mapIdx( idx, extent); } } } <commit_msg>Fixed copy paste failure for mapidx 4D case<commit_after>/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * alpaka is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <alpaka/vec/Vec.hpp> // Vec #include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC #if !defined(__CUDA_ARCH__) #include <boost/core/ignore_unused.hpp> // boost::ignore_unused #endif namespace alpaka { namespace core { namespace detail { //############################################################################# //! Maps a linear index to a N dimensional index. //############################################################################# template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TSfinae = void> struct MapIdx; //############################################################################# //! Maps a 1 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<1u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { #if !defined(__CUDA_ARCH__) boost::ignore_unused(extent); #endif return idx; } }; //############################################################################# //! Maps a 1 dimensional index to a 2 dimensional index. //############################################################################# template<> struct MapIdx< 2u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 2 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<2u>, TElem> const & extent) -> Vec<dim::DimInt<2u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[1u]); return { static_cast<TElem>(idx1d / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 1 dimensional index to a 3 dimensional index. //############################################################################# template<> struct MapIdx< 3u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 3 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<3u>, TElem> const & extent) -> Vec<dim::DimInt<3u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[2]); TElem const xyExtentProd(extent[2u] * extent[1u]); return { static_cast<TElem>(idx1d / xyExtentProd), static_cast<TElem>((idx1d % xyExtentProd) / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 1 dimensional index to a 4 dimensional index. //############################################################################# template<> struct MapIdx< 4u, 1u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 4 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<1u>, TElem> const & idx, Vec<dim::DimInt<4u>, TElem> const & extent) -> Vec<dim::DimInt<4u>, TElem> { TElem const & idx1d(idx[0u]); TElem const & extentX(extent[3]); TElem const xyExtentProd(extent[3u] * extent[2u]); TElem const xyzExtentProd(xyExtentProd * extent[1u]); return { static_cast<TElem>(idx1d / xyzExtentProd), static_cast<TElem>((idx1d % xyzExtentProd) / xyExtentProd), static_cast<TElem>((idx1d % xyExtentProd) / extentX), static_cast<TElem>(idx1d % extentX)}; } }; //############################################################################# //! Maps a 2 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 2u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<2u>, TElem> const & idx, Vec<dim::DimInt<2u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { idx[0u] * extent[1u] + idx[1u]}; } }; //############################################################################# //! Maps a 3 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 3u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<3u>, TElem> const & idx, Vec<dim::DimInt<3u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { (idx[0u] * extent[1u] + idx[1u]) * extent[2u] + idx[2u]}; } }; //############################################################################# //! Maps a 4 dimensional index to a 1 dimensional index. //############################################################################# template<> struct MapIdx< 1u, 4u> { //----------------------------------------------------------------------------- // \tparam TElem Type of the index values. // \param idx Idx to be mapped. // \param extent Spatial size to map the index to. // \return A 1 dimensional vector. //----------------------------------------------------------------------------- ALPAKA_NO_HOST_ACC_WARNING template< typename TElem> ALPAKA_FN_HOST_ACC static auto mapIdx( Vec<dim::DimInt<4u>, TElem> const & idx, Vec<dim::DimInt<4u>, TElem> const & extent) -> Vec<dim::DimInt<1u>, TElem> { return { ((idx[0u] * extent[1u] + idx[1u]) * extent[2u] + idx[2u]) * extent[3u] + idx[3u]}; } }; } //############################################################################# //! Maps a N dimensional index to a N dimensional position. //! //! \tparam TidxDimOut Dimension of the index vector to map to. //! \tparam TidxDimIn Dimension of the index vector to map from. //! \tparam TElem Type of the elements of the index vector to map from. //############################################################################# ALPAKA_NO_HOST_ACC_WARNING template< std::size_t TidxDimOut, std::size_t TidxDimIn, typename TElem> ALPAKA_FN_HOST_ACC auto mapIdx( Vec<dim::DimInt<TidxDimIn>, TElem> const & idx, Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent) -> Vec<dim::DimInt<TidxDimOut>, TElem> { return detail::MapIdx< TidxDimOut, TidxDimIn> ::mapIdx( idx, extent); } } } <|endoftext|>
<commit_before>/** * These codes are licensed under the Unlicense. * http://unlicense.org */ #ifndef COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #define COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #include <cassert> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <ostream> #include <sstream> #include <streambuf> #include <string> #include <type_traits> #include <utility> #include "formatted_output.hpp" #include "typing_aid.hpp" namespace commata { class text_error_info; class text_error : public std::exception { struct what_holder { virtual ~what_holder() {} virtual const char* what() const noexcept = 0; }; template <class Tr = std::char_traits<char>, class Allocator = std::allocator<char>> class string_holder : public what_holder { std::basic_string<char, Tr, Allocator> s_; public: template <class T> explicit string_holder(T&& s) : s_(std::forward<T>(s)) {} string_holder(const string_holder&) = delete; ~string_holder() = default; const char* what() const noexcept override { return s_.c_str(); } }; std::shared_ptr<what_holder> what_; std::pair<std::size_t, std::size_t> pos_; public: static constexpr std::size_t npos = static_cast<std::size_t>(-1); text_error() noexcept : pos_(npos, npos) {} template <class Tr> explicit text_error(std::basic_string_view<char, Tr> what_arg) : text_error(std::string(what_arg.cbegin(), what_arg.cend())) {} template <class Tr, class Allocator> explicit text_error(std::basic_string<char, Tr, Allocator>&& what_arg) : what_(std::make_shared<string_holder<Tr, Allocator>>( std::move(what_arg))), pos_(npos, npos) {} explicit text_error(const char* what_arg) : text_error(std::string(what_arg)) {} text_error(const text_error& other) = default; text_error(text_error&& other) = default; text_error& operator=(const text_error& other) noexcept { std::exception::operator=(other); what_ = other.what_; pos_ = other.pos_; // According to C++17 23.4.2 (1), pair's copy assignment does not throw // but are not marked as noexcept return *this; } text_error& operator=(text_error&& other) = default; const char* what() const noexcept override { return what_ ? what_->what() : ""; } text_error& set_physical_position( std::size_t line = npos, std::size_t col = npos) noexcept { pos_ = std::make_pair(line, col); return *this; } const std::pair<std::size_t, std::size_t>* get_physical_position() const noexcept { return (pos_ != std::make_pair(npos, npos)) ? &pos_ : nullptr; } text_error_info info(std::size_t base = 1U) const noexcept; }; class text_error_info { const text_error* ex_; std::size_t base_; public: text_error_info(const text_error& ex, std::size_t base) noexcept : ex_(std::addressof(ex)), base_(base) {} text_error_info(const text_error_info& ex) = default; text_error_info& operator=(const text_error_info& ex) = default; const text_error& error() const noexcept { return *ex_; } std::size_t get_base() const noexcept { return base_; } }; inline text_error_info text_error::info(std::size_t base) const noexcept { return text_error_info(*this, base); } namespace detail::ex { using length_t = std::common_type_t<std::make_unsigned_t<std::streamsize>, std::size_t>; constexpr std::streamsize nmax = std::numeric_limits<std::streamsize>::max(); constexpr length_t unmax = static_cast<length_t>(nmax); // Prints a non-negative integer value in the decimal system // into a sufficient-length buffer template <std::size_t N> std::size_t print_pos(char (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::snprintf(s, N, "%zu", pos + base) : std::snprintf(s, N, "n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::size_t>(len); } template <std::size_t N> std::size_t print_pos(wchar_t (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::swprintf(s, N, L"%zu", pos + base) : std::swprintf(s, N, L"n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::size_t>(len); } template <class Ch, class Tr> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch* s, std::size_t n) { if constexpr (std::numeric_limits<std::size_t>::max() > unmax) { while (n > unmax) { if (sb->sputn(s, nmax) != nmax) { return false; } s += unmax; n -= static_cast<std::size_t>(unmax); // safe because n > unmax } } return sb->sputn(s, n) == static_cast<std::streamsize>(n); } template <class Ch, class Tr, std::size_t N> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch(&s)[N]) { // s shall be null terminated, so s[N - 1] is null assert(s[N - 1] == Ch()); return sputn(sb, s, N - 1); } template <class T> std::pair<T, bool> add(T a, T b) { if (std::numeric_limits<T>::max() - a >= b) { return { a + b, true }; } else { return { T(), false }; } } template <class T, class... Ts> std::pair<T, bool> add(T a, T b, Ts... cs) { const auto bcs = add<T>(b, cs...); if (bcs.second) { return add<T>(a, bcs.first); } else { return { T(), false }; } } } // end detail::ex template <class Tr> std::basic_ostream<char, Tr>& operator<<( std::basic_ostream<char, Tr>& os, const text_error_info& i) { using namespace detail::ex; if (const auto p = i.error().get_physical_position()) { // line char l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = print_pos(l, p->first, i.get_base()); // column char c[sizeof(l)]; const auto c_len = print_pos(c, p->second, i.get_base()); // what const auto w = i.error().what(); const auto w_len = std::strlen(w); const auto n = add<length_t>( w_len, l_len, c_len, ((w_len > 0) ? 15 : 27)).first; return detail::formatted_output(os, static_cast<std::streamsize>(n), [w, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { if (!sputn(sb, w, w_len) || !sputn(sb, "; line ")) { return false; } } else if (!sputn(sb, "Text error at line ")) { return false; } return sputn(sb, l, l_len) && sputn(sb, " column ") && sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } template <class Tr> std::basic_ostream<wchar_t, Tr>& operator<<( std::basic_ostream<wchar_t, Tr>& os, const text_error_info& i) { using namespace detail::ex; if (const auto p = i.error().get_physical_position()) { // line wchar_t l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = print_pos(l, p->first, i.get_base()); // column wchar_t c[std::size(l)]; const auto c_len = print_pos(c, p->second, i.get_base()); // what const auto w_raw = i.error().what(); const auto w_len = std::strlen(w_raw); const auto n = add<length_t>( w_len, l_len, c_len, ((w_len > 0) ? 15 : 27)).first; return detail::formatted_output(os, static_cast<std::streamsize>(n), [&os, w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { for (std::size_t j = 0; j < w_len; ++j) { if (sb->sputc(os.widen(w_raw[j])) == Tr::eof()) { return false; } } if (!sputn(sb, L"; line ")) { return false; } } else if (!sputn(sb, L"Text error at line ")) { return false; } return sputn(sb, l, l_len) && sputn(sb, L" column ") && sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } inline std::string to_string(const text_error_info& i) { std::ostringstream s; s << i; return std::move(s).str(); } inline std::wstring to_wstring(const text_error_info& i) { std::wostringstream s; s << i; return std::move(s).str(); } } #endif <commit_msg>Employ std::optional for overflow-aware addition for text_error_info<commit_after>/** * These codes are licensed under the Unlicense. * http://unlicense.org */ #ifndef COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #define COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #include <cassert> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <optional> #include <ostream> #include <sstream> #include <streambuf> #include <string> #include <type_traits> #include <utility> #include "formatted_output.hpp" #include "typing_aid.hpp" namespace commata { class text_error_info; class text_error : public std::exception { struct what_holder { virtual ~what_holder() {} virtual const char* what() const noexcept = 0; }; template <class Tr = std::char_traits<char>, class Allocator = std::allocator<char>> class string_holder : public what_holder { std::basic_string<char, Tr, Allocator> s_; public: template <class T> explicit string_holder(T&& s) : s_(std::forward<T>(s)) {} string_holder(const string_holder&) = delete; ~string_holder() = default; const char* what() const noexcept override { return s_.c_str(); } }; std::shared_ptr<what_holder> what_; std::pair<std::size_t, std::size_t> pos_; public: static constexpr std::size_t npos = static_cast<std::size_t>(-1); text_error() noexcept : pos_(npos, npos) {} template <class Tr> explicit text_error(std::basic_string_view<char, Tr> what_arg) : text_error(std::string(what_arg.cbegin(), what_arg.cend())) {} template <class Tr, class Allocator> explicit text_error(std::basic_string<char, Tr, Allocator>&& what_arg) : what_(std::make_shared<string_holder<Tr, Allocator>>( std::move(what_arg))), pos_(npos, npos) {} explicit text_error(const char* what_arg) : text_error(std::string(what_arg)) {} text_error(const text_error& other) = default; text_error(text_error&& other) = default; text_error& operator=(const text_error& other) noexcept { std::exception::operator=(other); what_ = other.what_; pos_ = other.pos_; // According to C++17 23.4.2 (1), pair's copy assignment does not throw // but are not marked as noexcept return *this; } text_error& operator=(text_error&& other) = default; const char* what() const noexcept override { return what_ ? what_->what() : ""; } text_error& set_physical_position( std::size_t line = npos, std::size_t col = npos) noexcept { pos_ = std::make_pair(line, col); return *this; } const std::pair<std::size_t, std::size_t>* get_physical_position() const noexcept { return (pos_ != std::make_pair(npos, npos)) ? &pos_ : nullptr; } text_error_info info(std::size_t base = 1U) const noexcept; }; class text_error_info { const text_error* ex_; std::size_t base_; public: text_error_info(const text_error& ex, std::size_t base) noexcept : ex_(std::addressof(ex)), base_(base) {} text_error_info(const text_error_info& ex) = default; text_error_info& operator=(const text_error_info& ex) = default; const text_error& error() const noexcept { return *ex_; } std::size_t get_base() const noexcept { return base_; } }; inline text_error_info text_error::info(std::size_t base) const noexcept { return text_error_info(*this, base); } namespace detail::ex { using length_t = std::common_type_t<std::make_unsigned_t<std::streamsize>, std::size_t>; constexpr std::streamsize nmax = std::numeric_limits<std::streamsize>::max(); constexpr length_t unmax = static_cast<length_t>(nmax); // Prints a non-negative integer value in the decimal system // into a sufficient-length buffer template <std::size_t N> std::size_t print_pos(char (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::snprintf(s, N, "%zu", pos + base) : std::snprintf(s, N, "n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::size_t>(len); } template <std::size_t N> std::size_t print_pos(wchar_t (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::swprintf(s, N, L"%zu", pos + base) : std::swprintf(s, N, L"n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::size_t>(len); } template <class Ch, class Tr> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch* s, std::size_t n) { if constexpr (std::numeric_limits<std::size_t>::max() > unmax) { while (n > unmax) { if (sb->sputn(s, nmax) != nmax) { return false; } s += unmax; n -= static_cast<std::size_t>(unmax); // safe because n > unmax } } return sb->sputn(s, n) == static_cast<std::streamsize>(n); } template <class Ch, class Tr, std::size_t N> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch(&s)[N]) { // s shall be null terminated, so s[N - 1] is null assert(s[N - 1] == Ch()); return sputn(sb, s, N - 1); } template <class T> std::optional<T> add(T a, T b) { if (std::numeric_limits<T>::max() - a >= b) { return a + b; } else { return std::nullopt; } } template <class T, class... Ts> std::optional<T> add(T a, T b, Ts... cs) { if (const auto bcs = add<T>(b, cs...)) { return add<T>(a, *bcs); } else { return std::nullopt; } } } // end detail::ex template <class Tr> std::basic_ostream<char, Tr>& operator<<( std::basic_ostream<char, Tr>& os, const text_error_info& i) { using namespace detail::ex; if (const auto p = i.error().get_physical_position()) { // line char l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = print_pos(l, p->first, i.get_base()); // column char c[sizeof(l)]; const auto c_len = print_pos(c, p->second, i.get_base()); // what const auto w = i.error().what(); const auto w_len = std::strlen(w); auto n = add<length_t>(w_len, l_len, c_len, ((w_len > 0) ? 15 : 27)); if (!n || (*n > unmax)) { // more than largest possible padding length, when 'no padding' // does the trick n = 0; } return detail::formatted_output(os, static_cast<std::streamsize>(*n), [w, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { if (!sputn(sb, w, w_len) || !sputn(sb, "; line ")) { return false; } } else if (!sputn(sb, "Text error at line ")) { return false; } return sputn(sb, l, l_len) && sputn(sb, " column ") && sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } template <class Tr> std::basic_ostream<wchar_t, Tr>& operator<<( std::basic_ostream<wchar_t, Tr>& os, const text_error_info& i) { using namespace detail::ex; if (const auto p = i.error().get_physical_position()) { // line wchar_t l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = print_pos(l, p->first, i.get_base()); // column wchar_t c[std::size(l)]; const auto c_len = print_pos(c, p->second, i.get_base()); // what const auto w_raw = i.error().what(); const auto w_len = std::strlen(w_raw); auto n = add<length_t>(w_len, l_len, c_len, ((w_len > 0) ? 15 : 27)); if (!n || (*n > unmax)) { // more than largest possible padding length, when 'no padding' // does the trick n = 0; } return detail::formatted_output(os, static_cast<std::streamsize>(*n), [&os, w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { for (std::size_t j = 0; j < w_len; ++j) { if (sb->sputc(os.widen(w_raw[j])) == Tr::eof()) { return false; } } if (!sputn(sb, L"; line ")) { return false; } } else if (!sputn(sb, L"Text error at line ")) { return false; } return sputn(sb, l, l_len) && sputn(sb, L" column ") && sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } inline std::string to_string(const text_error_info& i) { std::ostringstream s; s << i; return std::move(s).str(); } inline std::wstring to_wstring(const text_error_info& i) { std::wostringstream s; s << i; return std::move(s).str(); } } #endif <|endoftext|>
<commit_before>/** * These codes are licensed under the Unlicense. * http://unlicense.org */ #ifndef COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #define COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #include <cassert> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <ostream> #include <sstream> #include <streambuf> #include <string> #include <type_traits> #include <utility> #include "formatted_output.hpp" #include "typing_aid.hpp" namespace commata { namespace detail { template <class T> struct npos_impl { constexpr static T npos = static_cast<T>(-1); }; // To define this in a header, npos_impl is a template template <class T> constexpr T npos_impl<T>::npos; } // end namespace detail class text_error; class text_error_info { const text_error* ex_; std::size_t base_; public: text_error_info(const text_error& ex, std::size_t base) noexcept : ex_(std::addressof(ex)), base_(base) {} text_error_info(const text_error_info& ex) = default; text_error_info& operator=(const text_error_info& ex) = default; const text_error& error() const noexcept { return *ex_; } std::size_t get_base() const noexcept { return base_; } }; class text_error : public std::exception, public detail::npos_impl<std::size_t> { struct what_holder { virtual ~what_holder() {} virtual const char* what() const noexcept = 0; }; template <class S> class string_holder : public what_holder { S s_; public: template <class T, class = std::enable_if_t<std::is_constructible<S, T>::value>> string_holder(T&& s) : s_(std::forward<T>(s)) {} ~string_holder() = default; string_holder(const string_holder&) = delete; const char* what() const noexcept override { return s_.c_str(); // std::basic_string<Ch, Tr, Allocator>::c_str is noexcept } }; std::shared_ptr<what_holder> what_; std::pair<std::size_t, std::size_t> physical_position_; public: template <class T, std::enable_if_t< detail::is_std_string_of<std::decay_t<T>, char>::value || std::is_constructible<std::string, T>::value, std::nullptr_t> = nullptr> explicit text_error(T&& what_arg) : what_(create_what( detail::is_std_string_of<std::decay_t<T>, char>(), std::forward<T>(what_arg))), physical_position_(npos, npos) {} private: template <class T> static auto create_what(std::true_type, T&& what_arg) { return std::allocate_shared<string_holder<std::decay_t<T>>>( what_arg.get_allocator(), std::forward<T>(what_arg)); } template <class T> static auto create_what(std::false_type, T&& what_arg) { return std::make_shared<string_holder<std::string>>( std::forward<T>(what_arg)); } public: text_error(const text_error& other) = default; text_error(text_error&& other) = default; text_error& operator=(const text_error& other) noexcept { std::exception::operator=(other); what_ = other.what_; physical_position_ = other.physical_position_; // According to C++14 20.3.2 (1), pair's assignments do not throw // but are not declared as noexcept return *this; } text_error& operator=(text_error&& other) noexcept { std::exception::operator=(std::move(other)); what_ = std::move(other.what_); physical_position_ = other.physical_position_; // ditto return *this; } const char* what() const noexcept override { return what_->what(); } text_error& set_physical_position( std::size_t line = npos, std::size_t col = npos) noexcept { physical_position_ = std::make_pair(line, col); return *this; } const std::pair<std::size_t, std::size_t>* get_physical_position() const noexcept { return (physical_position_ != std::make_pair(npos, npos)) ? &physical_position_ : nullptr; } text_error_info info(std::size_t base = 1U) const noexcept { return text_error_info(*this, base); } }; namespace detail { // Prints a non-negative integer value in the decimal system // into a sufficient-length buffer template <std::size_t N> std::streamsize print_pos(char (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) ? std::snprintf(s, N, "%zu", pos + base) : std::snprintf(s, N, "n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::streamsize>(len); } template <std::size_t N> std::streamsize print_pos(wchar_t (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) ? std::swprintf(s, N, L"%zu", pos + base) : std::swprintf(s, N, L"n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::streamsize>(len); } template <class Ch, class Tr, std::size_t N> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch(&s)[N]) { // s shall be null terminated, so s[N - 1] is null return sb->sputn(s, N - 1) == N - 1; } template <class Ch, class Tr> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch* s, std::streamsize n) { return sb->sputn(s, n) == n; } } // end namespace detail template <class Tr> std::basic_ostream<char, Tr>& operator<<( std::basic_ostream<char, Tr>& os, const text_error_info& i) { if (const auto p = i.error().get_physical_position()) { // line char l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = detail::print_pos(l, p->first, i.get_base()); // column char c[sizeof(l)]; const auto c_len = detail::print_pos(c, p->second, i.get_base()); // what const auto w = i.error().what(); const auto w_len = static_cast<std::streamsize>(std::strlen(w)); const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27); return detail::formatted_output(os, n, [w, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { if (!detail::sputn(sb, w, w_len) || !detail::sputn(sb, "; line ")) { return false; } } else if (!detail::sputn(sb, "Text error at line ")) { return false; } return detail::sputn(sb, l, l_len) && detail::sputn(sb, " column ") && detail::sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } template <class Tr> std::basic_ostream<wchar_t, Tr>& operator<<( std::basic_ostream<wchar_t, Tr>& os, const text_error_info& i) { if (const auto p = i.error().get_physical_position()) { // line wchar_t l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = detail::print_pos(l, p->first, i.get_base()); // column wchar_t c[sizeof(l) / sizeof(wchar_t)]; const auto c_len = detail::print_pos(c, p->second, i.get_base()); // what const auto w_raw = i.error().what(); const auto w_len = static_cast<std::streamsize>(std::strlen(w_raw)); const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27); return detail::formatted_output(os, n, [&os, w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { for (std::streamsize j = 0; j < w_len; ++j) { if (sb->sputc(os.widen(w_raw[j])) == Tr::eof()) { return false; } } if (!detail::sputn(sb, L"; line ")) { return false; } } else if (!detail::sputn(sb, L"Text error at line ")) { return false; } return detail::sputn(sb, l, l_len) && detail::sputn(sb, L" column ") && detail::sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } inline std::string to_string(const text_error_info& i) { std::ostringstream s; s << i; return s.str(); } inline std::wstring to_wstring(const text_error_info& i) { std::wostringstream s; s << i; return s.str(); } } #endif <commit_msg>text_error_info: take care of wrap-around<commit_after>/** * These codes are licensed under the Unlicense. * http://unlicense.org */ #ifndef COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #define COMMATA_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7 #include <cassert> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <ostream> #include <sstream> #include <streambuf> #include <string> #include <type_traits> #include <utility> #include "formatted_output.hpp" #include "typing_aid.hpp" namespace commata { namespace detail { template <class T> struct npos_impl { constexpr static T npos = static_cast<T>(-1); }; // To define this in a header, npos_impl is a template template <class T> constexpr T npos_impl<T>::npos; } // end namespace detail class text_error; class text_error_info { const text_error* ex_; std::size_t base_; public: text_error_info(const text_error& ex, std::size_t base) noexcept : ex_(std::addressof(ex)), base_(base) {} text_error_info(const text_error_info& ex) = default; text_error_info& operator=(const text_error_info& ex) = default; const text_error& error() const noexcept { return *ex_; } std::size_t get_base() const noexcept { return base_; } }; class text_error : public std::exception, public detail::npos_impl<std::size_t> { struct what_holder { virtual ~what_holder() {} virtual const char* what() const noexcept = 0; }; template <class S> class string_holder : public what_holder { S s_; public: template <class T, class = std::enable_if_t<std::is_constructible<S, T>::value>> string_holder(T&& s) : s_(std::forward<T>(s)) {} ~string_holder() = default; string_holder(const string_holder&) = delete; const char* what() const noexcept override { return s_.c_str(); // std::basic_string<Ch, Tr, Allocator>::c_str is noexcept } }; std::shared_ptr<what_holder> what_; std::pair<std::size_t, std::size_t> physical_position_; public: template <class T, std::enable_if_t< detail::is_std_string_of<std::decay_t<T>, char>::value || std::is_constructible<std::string, T>::value, std::nullptr_t> = nullptr> explicit text_error(T&& what_arg) : what_(create_what( detail::is_std_string_of<std::decay_t<T>, char>(), std::forward<T>(what_arg))), physical_position_(npos, npos) {} private: template <class T> static auto create_what(std::true_type, T&& what_arg) { return std::allocate_shared<string_holder<std::decay_t<T>>>( what_arg.get_allocator(), std::forward<T>(what_arg)); } template <class T> static auto create_what(std::false_type, T&& what_arg) { return std::make_shared<string_holder<std::string>>( std::forward<T>(what_arg)); } public: text_error(const text_error& other) = default; text_error(text_error&& other) = default; text_error& operator=(const text_error& other) noexcept { std::exception::operator=(other); what_ = other.what_; physical_position_ = other.physical_position_; // According to C++14 20.3.2 (1), pair's assignments do not throw // but are not declared as noexcept return *this; } text_error& operator=(text_error&& other) noexcept { std::exception::operator=(std::move(other)); what_ = std::move(other.what_); physical_position_ = other.physical_position_; // ditto return *this; } const char* what() const noexcept override { return what_->what(); } text_error& set_physical_position( std::size_t line = npos, std::size_t col = npos) noexcept { physical_position_ = std::make_pair(line, col); return *this; } const std::pair<std::size_t, std::size_t>* get_physical_position() const noexcept { return (physical_position_ != std::make_pair(npos, npos)) ? &physical_position_ : nullptr; } text_error_info info(std::size_t base = 1U) const noexcept { return text_error_info(*this, base); } }; namespace detail { // Prints a non-negative integer value in the decimal system // into a sufficient-length buffer template <std::size_t N> std::streamsize print_pos(char (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::snprintf(s, N, "%zu", pos + base) : std::snprintf(s, N, "n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::streamsize>(len); } template <std::size_t N> std::streamsize print_pos(wchar_t (&s)[N], std::size_t pos, std::size_t base) { const auto len = (pos != text_error::npos) && (text_error::npos - base >= pos) ? std::swprintf(s, N, L"%zu", pos + base) : std::swprintf(s, N, L"n/a"); assert((len > 0 ) && (static_cast<std::size_t>(len) < N)); return static_cast<std::streamsize>(len); } template <class Ch, class Tr, std::size_t N> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch(&s)[N]) { // s shall be null terminated, so s[N - 1] is null return sb->sputn(s, N - 1) == N - 1; } template <class Ch, class Tr> bool sputn(std::basic_streambuf<Ch, Tr>* sb, const Ch* s, std::streamsize n) { return sb->sputn(s, n) == n; } } // end namespace detail template <class Tr> std::basic_ostream<char, Tr>& operator<<( std::basic_ostream<char, Tr>& os, const text_error_info& i) { if (const auto p = i.error().get_physical_position()) { // line char l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = detail::print_pos(l, p->first, i.get_base()); // column char c[sizeof(l)]; const auto c_len = detail::print_pos(c, p->second, i.get_base()); // what const auto w = i.error().what(); const auto w_len = static_cast<std::streamsize>(std::strlen(w)); const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27); return detail::formatted_output(os, n, [w, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { if (!detail::sputn(sb, w, w_len) || !detail::sputn(sb, "; line ")) { return false; } } else if (!detail::sputn(sb, "Text error at line ")) { return false; } return detail::sputn(sb, l, l_len) && detail::sputn(sb, " column ") && detail::sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } template <class Tr> std::basic_ostream<wchar_t, Tr>& operator<<( std::basic_ostream<wchar_t, Tr>& os, const text_error_info& i) { if (const auto p = i.error().get_physical_position()) { // line wchar_t l[std::numeric_limits<std::size_t>::digits10 + 2]; const auto l_len = detail::print_pos(l, p->first, i.get_base()); // column wchar_t c[sizeof(l) / sizeof(wchar_t)]; const auto c_len = detail::print_pos(c, p->second, i.get_base()); // what const auto w_raw = i.error().what(); const auto w_len = static_cast<std::streamsize>(std::strlen(w_raw)); const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27); return detail::formatted_output(os, n, [&os, w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len] (auto* sb) { if (w_len > 0) { for (std::streamsize j = 0; j < w_len; ++j) { if (sb->sputc(os.widen(w_raw[j])) == Tr::eof()) { return false; } } if (!detail::sputn(sb, L"; line ")) { return false; } } else if (!detail::sputn(sb, L"Text error at line ")) { return false; } return detail::sputn(sb, l, l_len) && detail::sputn(sb, L" column ") && detail::sputn(sb, c, c_len); }); } else { return os << i.error().what(); } } inline std::string to_string(const text_error_info& i) { std::ostringstream s; s << i; return s.str(); } inline std::wstring to_wstring(const text_error_info& i) { std::wostringstream s; s << i; return s.str(); } } #endif <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/Texture.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_TEXTURE_HPP #define EOS_TEXTURE_HPP #include "eos/core/Image.hpp" #include "eos/core/image/resize.hpp" #include <algorithm> #include <vector> namespace eos { namespace render { // TODO: Should go to detail:: namespace, or texturing/utils or whatever. inline unsigned int get_max_possible_mipmaps_num(unsigned int width, unsigned int height) { unsigned int mipmapsNum = 1; unsigned int size = std::max(width, height); if (size == 1) return 1; do { size >>= 1; mipmapsNum++; } while (size != 1); return mipmapsNum; }; inline bool is_power_of_two(int x) { return !(x & (x - 1)); }; /** * @brief Represents a texture for rendering. * * Represents a texture and mipmap levels for use in the renderer. * Todo: This whole class needs a major overhaul and documentation. */ class Texture { public: std::vector<eos::core::Image4u> mipmaps; // make Texture a friend class of renderer, then move this to private? unsigned char widthLog, heightLog; // log2 of width and height of the base mip-level // private: // std::string filename; unsigned int mipmaps_num; }; // throws: ocv exc, runtime_ex inline Texture create_mipmapped_texture(const eos::core::Image4u& image, unsigned int mipmapsNum = 0) { Texture texture; texture.mipmaps_num = (mipmapsNum == 0 ? get_max_possible_mipmaps_num(image.width(), image.height()) : mipmapsNum); /*if (mipmapsNum == 0) { uchar mmn = render::utils::MatrixUtils::getMaxPossibleMipmapsNum(image.cols, image.rows); this->mipmapsNum = mmn; } else { this->mipmapsNum = mipmapsNum; }*/ if (texture.mipmaps_num > 1) { if (!is_power_of_two(image.width()) || !is_power_of_two(image.height())) { throw std::runtime_error("Error: Couldn't generate mipmaps, width or height not power of two."); } } int currWidth = image.width(); int currHeight = image.height(); std::vector<eos::core::Image4u> mipmaps; for (unsigned int i = 0; i < texture.mipmaps_num; i++) { if (i == 0) { mipmaps.push_back(image); } else { const eos::core::Image4u currMipMap = eos::core::image::resize(mipmaps[i - 1], currWidth, currHeight); mipmaps.push_back(currMipMap); } if (currWidth > 1) currWidth >>= 1; if (currHeight > 1) currHeight >>= 1; } texture.mipmaps = mipmaps; constexpr double ln2 = 0.69314718056; texture.widthLog = (unsigned char)(std::log(mipmaps[0].width()) / ln2 + 0.0001f); // std::epsilon or something? or why 0.0001f here? texture.heightLog = (unsigned char)( std::log(mipmaps[0].height()) / ln2 + 0.0001f); // Changed std::logf to std::log because it doesnt compile in linux (gcc 4.8). CHECK THAT return texture; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_TEXTURE_HPP */ <commit_msg>Ran clang-format on Texture.hpp<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/render/Texture.hpp * * Copyright 2017 Patrik Huber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef EOS_TEXTURE_HPP #define EOS_TEXTURE_HPP #include "eos/core/Image.hpp" #include "eos/core/image/resize.hpp" #include <algorithm> #include <vector> namespace eos { namespace render { // TODO: Should go to detail:: namespace, or texturing/utils or whatever. inline unsigned int get_max_possible_mipmaps_num(unsigned int width, unsigned int height) { unsigned int mipmapsNum = 1; unsigned int size = std::max(width, height); if (size == 1) return 1; do { size >>= 1; mipmapsNum++; } while (size != 1); return mipmapsNum; }; inline bool is_power_of_two(int x) { return !(x & (x - 1)); }; /** * @brief Represents a texture for rendering. * * Represents a texture and mipmap levels for use in the renderer. * Todo: This whole class needs a major overhaul and documentation. */ class Texture { public: std::vector<eos::core::Image4u> mipmaps; // make Texture a friend class of renderer, then move this to private? unsigned char widthLog, heightLog; // log2 of width and height of the base mip-level // private: // std::string filename; unsigned int mipmaps_num; }; // throws: ocv exc, runtime_ex inline Texture create_mipmapped_texture(const eos::core::Image4u& image, unsigned int mipmapsNum = 0) { Texture texture; texture.mipmaps_num = (mipmapsNum == 0 ? get_max_possible_mipmaps_num(image.width(), image.height()) : mipmapsNum); /*if (mipmapsNum == 0) { uchar mmn = render::utils::MatrixUtils::getMaxPossibleMipmapsNum(image.cols, image.rows); this->mipmapsNum = mmn; } else { this->mipmapsNum = mipmapsNum; }*/ if (texture.mipmaps_num > 1) { if (!is_power_of_two(image.width()) || !is_power_of_two(image.height())) { throw std::runtime_error("Error: Couldn't generate mipmaps, width or height not power of two."); } } int currWidth = image.width(); int currHeight = image.height(); std::vector<eos::core::Image4u> mipmaps; for (unsigned int i = 0; i < texture.mipmaps_num; i++) { if (i == 0) { mipmaps.push_back(image); } else { const eos::core::Image4u currMipMap = eos::core::image::resize(mipmaps[i - 1], currWidth, currHeight); mipmaps.push_back(currMipMap); } if (currWidth > 1) currWidth >>= 1; if (currHeight > 1) currHeight >>= 1; } texture.mipmaps = mipmaps; constexpr double ln2 = 0.69314718056; texture.widthLog = (unsigned char)(std::log(mipmaps[0].width()) / ln2 + 0.0001f); // std::epsilon or something? or why 0.0001f here? texture.heightLog = (unsigned char)(std::log(mipmaps[0].height()) / ln2 + 0.0001f); // Changed std::logf to std::log because it doesnt compile // in linux (gcc 4.8). CHECK THAT return texture; }; } /* namespace render */ } /* namespace eos */ #endif /* EOS_TEXTURE_HPP */ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifdef ETL_BLAS_MODE extern "C" { #include "cblas.h" } #endif namespace etl { namespace impl { namespace blas { #ifdef ETL_BLAS_MODE /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_single_precision<A, B, C>::value)> void gemm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; cblas_sgemm( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, CblasNoTrans, etl::rows(a), etl::columns(b), etl::columns(a), 1.0f, a.memory_start(), major_stride(a), b.memory_start(), major_stride(b), 0.0f, c.memory_start(), major_stride(c)); } /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_double_precision<A, B, C>::value)> void gemm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; cblas_dgemm( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, CblasNoTrans, etl::rows(a), etl::columns(b), etl::columns(a), 1.0, a.memory_start(), major_stride(a), b.memory_start(), major_stride(b), 0.0, c.memory_start(), major_stride(c)); } /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_single_precision<A, B, C>::value)> void gemm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; std::complex<float> alpha(1.0, 0.0); std::complex<float> beta(0.0, 0.0); cblas_cgemm( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, CblasNoTrans, etl::rows(a), etl::columns(b), etl::columns(a), &alpha, a.memory_start(), major_stride(a), b.memory_start(), major_stride(b), &beta, c.memory_start(), major_stride(c)); } /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_double_precision<A, B, C>::value)> void gemm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; std::complex<double> alpha(1.0, 0.0); std::complex<double> beta(0.0, 0.0); cblas_zgemm( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, CblasNoTrans, etl::rows(a), etl::columns(b), etl::columns(a), &alpha, a.memory_start(), major_stride(a), b.memory_start(), major_stride(b), &beta, c.memory_start(), major_stride(c)); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_double_precision<A, B, C>::value)> void gemv(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; cblas_dgemv( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, etl::rows(a), etl::columns(a), 1.0, a.memory_start(), major_stride(a), b.memory_start(), 1, 0.0, c.memory_start(), 1); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_single_precision<A, B, C>::value)> void gemv(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; cblas_sgemv( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, etl::rows(a), etl::columns(a), 1.0, a.memory_start(), major_stride(a), b.memory_start(), 1, 0.0, c.memory_start(), 1); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_single_precision<A, B, C>::value)> void gemv(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; std::complex<float> alpha(1.0, 0.0); std::complex<float> beta(0.0, 0.0); cblas_cgemv( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, etl::rows(a), etl::columns(a), &alpha, a.memory_start(), major_stride(a), b.memory_start(), 1, &beta, c.memory_start(), 1); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_double_precision<A, B, C>::value)> void gemv(A&& a, B&& b, C&& c) { bool row_major = decay_traits<A>::storage_order == order::RowMajor; std::complex<double> alpha(1.0, 0.0); std::complex<double> beta(0.0, 0.0); cblas_zgemv( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, etl::rows(a), etl::columns(a), &alpha, a.memory_start(), major_stride(a), b.memory_start(), 1, &beta, c.memory_start(), 1); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_double_precision<A, B, C>::value)> void gevm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<B>::storage_order == order::RowMajor; cblas_dgemv( row_major ? CblasRowMajor : CblasColMajor, CblasTrans, etl::rows(b), etl::columns(b), 1.0, b.memory_start(), major_stride(b), a.memory_start(), 1, 0.0, c.memory_start(), 1); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_single_precision<A, B, C>::value)> void gevm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<B>::storage_order == order::RowMajor; cblas_sgemv( row_major ? CblasRowMajor : CblasColMajor, CblasTrans, etl::rows(b), etl::columns(b), 1.0, b.memory_start(), major_stride(b), a.memory_start(), 1, 0.0, c.memory_start(), 1); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_single_precision<A, B, C>::value)> void gevm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<B>::storage_order == order::RowMajor; std::complex<float> alpha(1.0, 0.0); std::complex<float> beta(0.0, 0.0); cblas_cgemv( row_major ? CblasRowMajor : CblasColMajor, CblasTrans, etl::rows(b), etl::columns(b), &alpha, b.memory_start(), major_stride(b), a.memory_start(), 1, &beta, c.memory_start(), 1); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C, cpp_enable_if(all_complex_double_precision<A, B, C>::value)> void gevm(A&& a, B&& b, C&& c) { bool row_major = decay_traits<B>::storage_order == order::RowMajor; std::complex<double> alpha(1.0, 0.0); std::complex<double> beta(0.0, 0.0); cblas_zgemv( row_major ? CblasRowMajor : CblasColMajor, CblasTrans, etl::rows(b), etl::columns(b), &alpha, b.memory_start(), major_stride(b), a.memory_start(), 1, &beta, c.memory_start(), 1); } #else //COVERAGE_EXCLUDE_BEGIN /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemm(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemv(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gevm(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } //COVERAGE_EXCLUDE_END #endif } //end of namespace blas } //end of namespace impl } //end of namespace etl <commit_msg>Cleanup BLAS gemm<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #ifdef ETL_BLAS_MODE extern "C" { #include "cblas.h" } #endif namespace etl { namespace impl { namespace blas { #ifdef ETL_BLAS_MODE // GEMM overloads inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const float alpha, const float* A, size_t lda, const float* B, size_t ldb, const float beta, float* C, size_t ldc) { cblas_sgemm(Layout, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const double alpha, const double* A, size_t lda, const double* B, size_t ldb, const double beta, double* C, size_t ldc) { cblas_dgemm(Layout, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const etl::complex<float> alpha, const etl::complex<float>* A, size_t lda, const etl::complex<float>* B, size_t ldb, const etl::complex<float> beta, etl::complex<float>* C, size_t ldc) { cblas_cgemm(Layout, TransA, TransB, M, N, K, &alpha, A, lda, B, ldb, &beta, C, ldc); } inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const etl::complex<double> alpha, const etl::complex<double>* A, size_t lda, const etl::complex<double>* B, size_t ldb, const etl::complex<double> beta, etl::complex<double>* C, size_t ldc) { cblas_zgemm(Layout, TransA, TransB, M, N, K, &alpha, A, lda, B, ldb, &beta, C, ldc); } inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const std::complex<float> alpha, const std::complex<float>* A, size_t lda, const std::complex<float>* B, size_t ldb, const std::complex<float> beta, std::complex<float>* C, size_t ldc) { cblas_cgemm(Layout, TransA, TransB, M, N, K, &alpha, A, lda, B, ldb, &beta, C, ldc); } inline void cblas_gemm(CBLAS_LAYOUT Layout, CBLAS_TRANSPOSE TransA, CBLAS_TRANSPOSE TransB, size_t M, size_t N, size_t K, const std::complex<double> alpha, const std::complex<double>* A, size_t lda, const std::complex<double>* B, size_t ldb, const std::complex<double> beta, std::complex<double>* C, size_t ldc) { cblas_zgemm(Layout, TransA, TransB, M, N, K, &alpha, A, lda, B, ldb, &beta, C, ldc); } // GEMV overloads inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const float alpha, const float *A, size_t lda, const float *X, size_t incX, const float beta, float *Y, size_t incY){ cblas_sgemv(Layout, TransA, M, N, alpha, A, lda, X, incX, beta, Y, incY); } inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const double alpha, const double *A, size_t lda, const double *X, size_t incX, const double beta, double *Y, size_t incY){ cblas_dgemv(Layout, TransA, M, N, alpha, A, lda, X, incX, beta, Y, incY); } inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const std::complex<float> alpha, const std::complex<float> *A, size_t lda, const std::complex<float> *X, size_t incX, const std::complex<float> beta, std::complex<float> *Y, size_t incY){ cblas_cgemv(Layout, TransA, M, N, &alpha, A, lda, X, incX, &beta, Y, incY); } inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const std::complex<double> alpha, const std::complex<double> *A, size_t lda, const std::complex<double> *X, size_t incX, const std::complex<double> beta, std::complex<double> *Y, size_t incY){ cblas_zgemv(Layout, TransA, M, N, &alpha, A, lda, X, incX, &beta, Y, incY); } inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const etl::complex<float> alpha, const etl::complex<float> *A, size_t lda, const etl::complex<float> *X, size_t incX, const etl::complex<float> beta, etl::complex<float> *Y, size_t incY){ cblas_cgemv(Layout, TransA, M, N, &alpha, A, lda, X, incX, &beta, Y, incY); } inline void cblas_gemv(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE TransA, size_t M, size_t N, const etl::complex<double> alpha, const etl::complex<double> *A, size_t lda, const etl::complex<double> *X, size_t incX, const etl::complex<double> beta, etl::complex<double> *Y, size_t incY){ cblas_zgemv(Layout, TransA, M, N, &alpha, A, lda, X, incX, &beta, Y, incY); } /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemm(A&& a, B&& b, C&& c) { using T = value_t<A>; static constexpr bool row_major = decay_traits<A>::storage_order == order::RowMajor; T alpha(1.0); T beta(0.0); cblas_gemm( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, CblasNoTrans, etl::rows(a), etl::columns(b), etl::columns(a), alpha, a.memory_start(), major_stride(a), b.memory_start(), major_stride(b), beta, c.memory_start(), major_stride(c)); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemv(A&& a, B&& b, C&& c) { using T = value_t<A>; static constexpr bool row_major = decay_traits<A>::storage_order == order::RowMajor; T alpha(1.0); T beta(0.0); cblas_gemv( row_major ? CblasRowMajor : CblasColMajor, CblasNoTrans, etl::rows(a), etl::columns(a), alpha, a.memory_start(), major_stride(a), b.memory_start(), 1, beta, c.memory_start(), 1); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gevm(A&& a, B&& b, C&& c) { using T = value_t<A>; static constexpr bool row_major = decay_traits<B>::storage_order == order::RowMajor; T alpha(1.0); T beta(0.0); cblas_gemv( row_major ? CblasRowMajor : CblasColMajor, CblasTrans, etl::rows(b), etl::columns(b), alpha, b.memory_start(), major_stride(b), a.memory_start(), 1, beta, c.memory_start(), 1); } #else //COVERAGE_EXCLUDE_BEGIN /*! * \brief Compute the matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemm(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } /*! * \brief Compute the matrix-vector mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gemv(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } /*! * \brief Compute the vector-matrix mutplication of a and b and store the result in c * param a The lhs of the multiplication * param b The rhs of the multiplication * param c The result */ template <typename A, typename B, typename C> void gevm(A&& a, B&& b, C&& c) { cpp_unused(a); cpp_unused(b); cpp_unused(c); cpp_unreachable("Unsupported feature called: blas gemm"); } //COVERAGE_EXCLUDE_END #endif } //end of namespace blas } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>#include <get_property_value.h> boost::python::object PyGetValue::GetObject() { return _obj; } boost::python::object PyGetValue::GetInteger( const IAAFPropertyValueSP& spPropVal, IAAFTypeDefIntSP& spTypeDef) { AxTypeDefInt axIntDef(spTypeDef); AxPropertyValue axValue(spPropVal); aafUInt32 size = axIntDef.GetSize(); if (axIntDef.IsSigned()) { if (sizeof(aafInt8) == size) return boost::python::object(GetInt<aafInt8>(axValue)); else if (sizeof(aafInt16) == size) return boost::python::object(GetInt<aafInt16>(axValue)); else if (sizeof(aafInt32) == size) return boost::python::object(GetInt<aafInt32>(axValue)); else return boost::python::object(GetInt<aafInt64>(axValue)); } else { if (sizeof(aafUInt8) == size) return boost::python::object(GetInt<aafUInt8>(axValue)); else if (sizeof(aafUInt16) == size) return boost::python::object(GetInt<aafUInt16>(axValue)); else if (sizeof(aafUInt32) == size) return boost::python::object(GetInt<aafUInt32>(axValue)); else return boost::python::object(GetInt<aafUInt64>(axValue)); } } void PyGetValue::processAny(IAAFPropertyValueSP& spPropVal) { AxPropertyValue axValue(spPropVal); IAAFTypeDefSP spTypeDef = axValue.GetType(); AxTypeDef axTypeDef(spTypeDef); if (axTypeDef.GetAUID() == kAAFTypeID_DateStruct) { aafDateStruct_t date = GetDate(axValue); _obj = boost::python::object( DateToString(date)); } else if (axTypeDef.GetAUID() == kAAFTypeID_TimeStruct) { _aafTimeStruct_t time = GetTime( axValue); _obj = boost::python::object(TimeToString(time)); } else if (axTypeDef.GetAUID() == kAAFTypeID_TimeStamp) { _aafTimeStamp_t timeStamp = GetTimeStamp(axValue); _obj = boost::python::object(TimeStampToString( timeStamp )); } else if (axTypeDef.GetAUID() == kAAFTypeID_AUID) { aafUID_t uid = GetUID( axValue); _obj = boost::python::object(uid); } else { eAAFTypeCategory_t cat = axTypeDef.GetTypeCategory(); switch( cat ) { #define CASE(T) \ case kAAFTypeCat##T : \ { \ IAAFTypeDef##T##SP sp; \ AxQueryInterface( axTypeDef.GetTypeDefSP(), sp ); \ this->process( spPropVal, sp ); \ break; \ } CASE( Int ) CASE( Character ) CASE( StrongObjRef ) CASE( WeakObjRef ) CASE( Rename ) CASE( Enum ) CASE( FixedArray ) // CASE( VariableArray ) CASE( Set ) CASE( Record ) CASE( Stream ) CASE( String ) CASE( ExtEnum ) CASE( Indirect ) CASE( Opaque ) CASE( VariableArray ) #undef CASE case kAAFTypeCatUnknown: // FIXME - What to do here? Get RawAccessType perhaps, but how is that // distinquished from encrypted using only the process() argument type? break; case kAAFTypeCatEncrypted: // FIXME - see kAAFTypeCatUnknown above. break; default: throw AxExBadImp( L"unknown type category" ); } } } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefCharacterSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefCharacterSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefIndirectSP& spTypeDef ) { AxTypeDefIndirect axIndirect( spTypeDef ); IAAFPropertyValueSP actualValueSP = axIndirect.GetActualValue(spPropVal); PyGetValue valueGetter; valueGetter.processAny(actualValueSP); _obj = valueGetter.GetObject(); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefIntSP& spTypeDef) { _obj = this->GetInteger(spPropVal,spTypeDef); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefRenameSP& spTypeDef) { AxTypeDefRename axTDR(spTypeDef); IAAFPropertyValueSP spRealValue = axTDR.GetBaseValue(spPropVal); PyGetValue valueGetter; valueGetter.processAny(spRealValue); _obj = valueGetter.GetObject(); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefEnumSP& spTypeDef) { AxTypeDefEnum axTDE(spTypeDef); aafUInt32 size = axTDE.CountElements(); boost::python::dict d; for ( aafUInt32 i = 0; i<size; i++ ) { AxString name = axTDE.GetElementName(i); aafInt64 id = axTDE.GetElementValue(i); d[name] = id; } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefExtEnumSP& spTypeDef) { AxTypeDefExtEnum axTDEE(spTypeDef); aafUInt32 size = axTDEE.CountElements(); boost::python::dict d; for ( aafUInt32 i = 0; i<size; i++ ) { AxString name = axTDEE.GetElementName(i); aafUID_t id = axTDEE.GetElementValue(i); d[name] = id; } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefFixedArraySP& spTypeDef) { AxTypeDefFixedArray axTDFA(spTypeDef); aafUInt32 size = axTDFA.GetCount(); std::wcout << size << "\n"; boost::python::list elements; for ( aafUInt32 i = 0; i<size; i++ ) { IAAFPropertyValueSP spElement = axTDFA.GetElementValue(spPropVal, i); PyGetValue valueGetter; valueGetter.processAny(spElement); elements.append(valueGetter.GetObject()); } _obj = elements; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefRecordSP& spTypeDef) { AxTypeDefRecord axTDR(spTypeDef); aafUInt32 size = axTDR.GetCount(); boost::python::dict d; for (aafUInt32 i = 0; i<size; i++) { AxString name = axTDR.GetMemberName(i); IAAFPropertyValueSP spValue = axTDR.GetValue(spPropVal, i); AxPropertyValue axValue(spValue); PyGetValue valueGetter; valueGetter.processAny(spValue); d[name] = valueGetter.GetObject(); //throw std::invalid_argument("Invalid AUID "); //std::wcout << axTDR.GetName() << " " << name << " " <<axDef.GetName() << "\n"; } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefSetSP& spTypeDef) { AxTypeDefSet axDefSet(spTypeDef); //_obj = boost::python::object(axDefSet.GetElements(spPropVal)); boost::python::list elements; AxPropertyValueIter axIter(axDefSet.GetElements(spPropVal)); bool notAtEnd =true; while (notAtEnd) { IAAFSmartPointer2<IAAFPropertyValue> nextValue; notAtEnd = axIter.NextOne(nextValue); if (notAtEnd) { IAAFPropertyValueSP spValue = nextValue; PyGetValue valueGetter; valueGetter.processAny(spValue); elements.append(valueGetter.GetObject()); } } _obj = elements; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStreamSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefStreamSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStringSP& spTypeDef) { AxTypeDefString axTypeDefString(spTypeDef); AxString value = axTypeDefString.GetElements( spPropVal ); _obj = boost::python::object(value); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStrongObjRefSP& spTypeDef) { AxTypeDefStrongObjRef axDefRef(spTypeDef); IAAFObjectSP spObj = axDefRef.GetObject<IAAFObject>(spPropVal); _obj = boost::python::object(spObj); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefWeakObjRefSP& spTypeDef) { AxTypeDefWeakObjRef axDefWRef(spTypeDef); AxClassDef axClasDef(axDefWRef.GetObjectType()); if (axClasDef.IsConcrete()) { IAAFObjectSP spObj = axDefWRef.GetObject<IAAFObject>(spPropVal); _obj = boost::python::object(spObj); } else { IAAFTypeDefSP spObj = axDefWRef.GetObject<IAAFTypeDef>(spPropVal); _obj = boost::python::object(spObj); } } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefObjectRefSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefObjectRefSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefOpaqueSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefOpaqueSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefVariableArraySP& spTypeDef) { AxTypeDefVariableArray axVarArray( spTypeDef ); aafUInt32 size = axVarArray.GetCount(spPropVal); AxPropertyValueIter axIter(axVarArray.GetElements(spPropVal)); bool notAtEnd = true; boost::python::list elements; for ( aafUInt32 i = 0; i<size; i++ ) { IAAFSmartPointer2<IAAFPropertyValue> nextValue; notAtEnd = axIter.NextOne(nextValue); if (notAtEnd) { IAAFPropertyValueSP spValue = nextValue; PyGetValue valueGetter; valueGetter.processAny(spValue); elements.append(valueGetter.GetObject()); } } _obj = elements; } <commit_msg>whitespace cleanup<commit_after>#include <get_property_value.h> boost::python::object PyGetValue::GetObject() { return _obj; } boost::python::object PyGetValue::GetInteger( const IAAFPropertyValueSP& spPropVal, IAAFTypeDefIntSP& spTypeDef) { AxTypeDefInt axIntDef(spTypeDef); AxPropertyValue axValue(spPropVal); aafUInt32 size = axIntDef.GetSize(); if (axIntDef.IsSigned()) { if (sizeof(aafInt8) == size) return boost::python::object(GetInt<aafInt8>(axValue)); else if (sizeof(aafInt16) == size) return boost::python::object(GetInt<aafInt16>(axValue)); else if (sizeof(aafInt32) == size) return boost::python::object(GetInt<aafInt32>(axValue)); else return boost::python::object(GetInt<aafInt64>(axValue)); } else { if (sizeof(aafUInt8) == size) return boost::python::object(GetInt<aafUInt8>(axValue)); else if (sizeof(aafUInt16) == size) return boost::python::object(GetInt<aafUInt16>(axValue)); else if (sizeof(aafUInt32) == size) return boost::python::object(GetInt<aafUInt32>(axValue)); else return boost::python::object(GetInt<aafUInt64>(axValue)); } } void PyGetValue::processAny(IAAFPropertyValueSP& spPropVal) { AxPropertyValue axValue(spPropVal); IAAFTypeDefSP spTypeDef = axValue.GetType(); AxTypeDef axTypeDef(spTypeDef); if (axTypeDef.GetAUID() == kAAFTypeID_DateStruct) { aafDateStruct_t date = GetDate(axValue); _obj = boost::python::object( DateToString(date)); } else if (axTypeDef.GetAUID() == kAAFTypeID_TimeStruct) { _aafTimeStruct_t time = GetTime( axValue); _obj = boost::python::object(TimeToString(time)); } else if (axTypeDef.GetAUID() == kAAFTypeID_TimeStamp) { _aafTimeStamp_t timeStamp = GetTimeStamp(axValue); _obj = boost::python::object(TimeStampToString( timeStamp )); } else if (axTypeDef.GetAUID() == kAAFTypeID_AUID) { aafUID_t uid = GetUID( axValue); _obj = boost::python::object(uid); } else { eAAFTypeCategory_t cat = axTypeDef.GetTypeCategory(); switch( cat ) { #define CASE(T) \ case kAAFTypeCat##T : \ { \ IAAFTypeDef##T##SP sp; \ AxQueryInterface( axTypeDef.GetTypeDefSP(), sp ); \ this->process( spPropVal, sp ); \ break; \ } CASE( Int ) CASE( Character ) CASE( StrongObjRef ) CASE( WeakObjRef ) CASE( Rename ) CASE( Enum ) CASE( FixedArray ) // CASE( VariableArray ) CASE( Set ) CASE( Record ) CASE( Stream ) CASE( String ) CASE( ExtEnum ) CASE( Indirect ) CASE( Opaque ) CASE( VariableArray ) #undef CASE case kAAFTypeCatUnknown: // FIXME - What to do here? Get RawAccessType perhaps, but how is that // distinquished from encrypted using only the process() argument type? break; case kAAFTypeCatEncrypted: // FIXME - see kAAFTypeCatUnknown above. break; default: throw AxExBadImp( L"unknown type category" ); } } } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefCharacterSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefCharacterSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefIndirectSP& spTypeDef ) { AxTypeDefIndirect axIndirect( spTypeDef ); IAAFPropertyValueSP actualValueSP = axIndirect.GetActualValue(spPropVal); PyGetValue valueGetter; valueGetter.processAny(actualValueSP); _obj = valueGetter.GetObject(); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefIntSP& spTypeDef) { _obj = this->GetInteger(spPropVal,spTypeDef); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefRenameSP& spTypeDef) { AxTypeDefRename axTDR(spTypeDef); IAAFPropertyValueSP spRealValue = axTDR.GetBaseValue(spPropVal); PyGetValue valueGetter; valueGetter.processAny(spRealValue); _obj = valueGetter.GetObject(); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefEnumSP& spTypeDef) { AxTypeDefEnum axTDE(spTypeDef); aafUInt32 size = axTDE.CountElements(); boost::python::dict d; for ( aafUInt32 i = 0; i<size; i++ ) { AxString name = axTDE.GetElementName(i); aafInt64 id = axTDE.GetElementValue(i); d[name] = id; } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefExtEnumSP& spTypeDef) { AxTypeDefExtEnum axTDEE(spTypeDef); aafUInt32 size = axTDEE.CountElements(); boost::python::dict d; for ( aafUInt32 i = 0; i<size; i++ ) { AxString name = axTDEE.GetElementName(i); aafUID_t id = axTDEE.GetElementValue(i); d[name] = id; } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefFixedArraySP& spTypeDef) { AxTypeDefFixedArray axTDFA(spTypeDef); aafUInt32 size = axTDFA.GetCount(); boost::python::list elements; for ( aafUInt32 i = 0; i<size; i++ ) { IAAFPropertyValueSP spElement = axTDFA.GetElementValue(spPropVal, i); PyGetValue valueGetter; valueGetter.processAny(spElement); elements.append(valueGetter.GetObject()); } _obj = elements; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefRecordSP& spTypeDef) { AxTypeDefRecord axTDR(spTypeDef); aafUInt32 size = axTDR.GetCount(); boost::python::dict d; for (aafUInt32 i = 0; i<size; i++) { AxString name = axTDR.GetMemberName(i); IAAFPropertyValueSP spValue = axTDR.GetValue(spPropVal, i); PyGetValue valueGetter; valueGetter.processAny(spValue); d[name] = valueGetter.GetObject(); } _obj = d; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefSetSP& spTypeDef) { AxTypeDefSet axDefSet(spTypeDef); boost::python::list elements; AxPropertyValueIter axIter(axDefSet.GetElements(spPropVal)); bool notAtEnd =true; while (notAtEnd) { IAAFSmartPointer2<IAAFPropertyValue> nextValue; notAtEnd = axIter.NextOne(nextValue); if (notAtEnd) { IAAFPropertyValueSP spValue = nextValue; PyGetValue valueGetter; valueGetter.processAny(spValue); elements.append(valueGetter.GetObject()); } } _obj = elements; } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStreamSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefStreamSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStringSP& spTypeDef) { AxTypeDefString axTypeDefString(spTypeDef); AxString value = axTypeDefString.GetElements( spPropVal ); _obj = boost::python::object(value); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefStrongObjRefSP& spTypeDef) { AxTypeDefStrongObjRef axDefRef(spTypeDef); IAAFObjectSP spObj = axDefRef.GetObject<IAAFObject>(spPropVal); _obj = boost::python::object(spObj); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefWeakObjRefSP& spTypeDef) { AxTypeDefWeakObjRef axDefWRef(spTypeDef); AxClassDef axClasDef(axDefWRef.GetObjectType()); if (axClasDef.IsConcrete()) { IAAFObjectSP spObj = axDefWRef.GetObject<IAAFObject>(spPropVal); _obj = boost::python::object(spObj); } else { IAAFTypeDefSP spObj = axDefWRef.GetObject<IAAFTypeDef>(spPropVal); _obj = boost::python::object(spObj); } } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefObjectRefSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefObjectRefSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefOpaqueSP& spTypeDef) { throw std::invalid_argument("IAAFTypeDefOpaqueSP Not Implemented"); } void PyGetValue::process( IAAFPropertyValueSP& spPropVal, IAAFTypeDefVariableArraySP& spTypeDef) { AxTypeDefVariableArray axVarArray( spTypeDef ); aafUInt32 size = axVarArray.GetCount(spPropVal); AxPropertyValueIter axIter(axVarArray.GetElements(spPropVal)); bool notAtEnd = true; boost::python::list elements; for ( aafUInt32 i = 0; i<size; i++ ) { IAAFSmartPointer2<IAAFPropertyValue> nextValue; notAtEnd = axIter.NextOne(nextValue); if (notAtEnd) { IAAFPropertyValueSP spValue = nextValue; PyGetValue valueGetter; valueGetter.processAny(spValue); elements.append(valueGetter.GetObject()); } } _obj = elements; } <|endoftext|>
<commit_before>// // Copyright (c) 2016 CNRS // Author: NMansard from Florent Lamiraux // // // This file is part of hpp-pinocchio // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_PINOCCHIO_JOINT_HH # define HPP_PINOCCHIO_JOINT_HH # include <cstddef> # include <hpp/fcl/math/transform.h> # include <hpp/pinocchio/config.hh> # include <hpp/pinocchio/fwd.hh> # include <hpp/pinocchio/fake-container.hh> namespace hpp { namespace pinocchio { /// Robot joint /// /// A joint maps an input vector to a transformation of SE(3) from the /// parent frame to the joint frame. /// /// The input vector is provided through the configuration vector of the /// robot the joint belongs to. The joint input vector is composed of the /// components of the robot configuration starting at /// Joint::rankInConfiguration. /// /// The joint input vector represents a element of a Lie group, either /// \li a vector space for JointTranslation, and bounded JointRotation, /// \li the unit circle for non-bounded JointRotation joints, /// \li an element of SO(3) for JointSO3, represented by a unit quaternion. /// /// Operations specific to joints (uniform sampling of input space, straight /// interpolation, distance, ...) are performed by a JointConfiguration /// instance that has the same class hierarchy as Joint. class HPP_PINOCCHIO_DLLAPI Joint { public: typedef se3::Index Index; /// \name Construction and copy and destruction /// \{ /// Constructor /// \param device pointer on the device the joint is belonging to. /// \param indexInJointList index of the joint, i.e. joint = device.model.joints[index] Joint (DevicePtr_t device, Index indexInJointList ); //DEPREC /// Constructor //DEPREC /// \param initialPosition position of the joint before being inserted //DEPREC /// in a kinematic chain, //DEPREC /// \param configSize dimension of the configuration vector, //DEPREC /// \param numberDof dimension of the velocity vector. //DEPREC Joint (const Transform3f& initialPosition, size_type configSize, //DEPREC size_type numberDof); //DEPREC /// Copy constructor //DEPREC /// //DEPREC /// Clone body and therefore inner and outer objects (see Body::clone). //DEPREC Joint (const Joint& joint); //DEPREC /// Return pointer to copy of this //DEPREC /// //DEPREC /// Clone body and therefore inner and outer objects (see Body::clone). //DEPREC virtual JointPtr_t clone () const = 0; //DEPREC virtual ~Joint (); ~Joint() {} /// \} // ----------------------------------------------------------------------- /// \name Name /// \{ //DEPREC /// Set name //DEPREC virtual inline void name(const std::string& name) /// Get name const std::string& name() const; /// \} // ----------------------------------------------------------------------- /// \name Position /// \{ //DEPREC /// Joint initial position (when robot is in zero configuration) //DEPREC const Transform3f& initialPosition () const; /// Joint transformation const Transform3f& currentTransformation () const; //DEPREC /// Compute position of joint //DEPREC /// \param configuration the configuration of the robot, //DEPREC /// \param parentPosition position of parent joint, //DEPREC /// \retval position position of this joint. //DEPREC virtual void computePosition (ConfigurationIn_t configuration, //DEPREC const Transform3f& parentPosition, //DEPREC Transform3f& position) const = 0; //DEPREC /// Compute position of this joint and all its descendents. //DEPREC void recursiveComputePosition (ConfigurationIn_t configuration, //DEPREC const Transform3f& parentPosition) const; //DEPREC /// Compute jacobian matrix of joint and all its descendents. //DEPREC void computeJacobian (); /// Get neutral configuration of joint //NOTYET vector_t neutralConfiguration () const; ///\} // ----------------------------------------------------------------------- /// \name Size and rank ///\} /// Return number of degrees of freedom size_type numberDof () const; /// Return number of degrees of freedom size_type configSize () const; /// Return rank of the joint in the configuration vector size_type rankInConfiguration () const; /// Return rank of the joint in the velocity vector size_type rankInVelocity () const; ///\} // ----------------------------------------------------------------------- /// \name Kinematic chain /// \{ /// Get a pointer to the parent joint (if any). // DEPREC JointPtr_t parentJoint () const //DEPREC /// Add child joint //DEPREC /// \param joint child joint added to this one, //DEPREC /// \param computePositionInParent whether to compute position of the //DEPREC /// child joint in this one's frame. //DEPREC /// //DEPREC /// \note When building a kinematic chain, we usually build the //DEPREC /// joint in its initial position and compute the (constant) //DEPREC /// position of the joint in its parent when adding the joint in //DEPREC /// the kinematic chain. When copying a kinematic chain, we copy the //DEPREC /// position of the joint in its parent frame and therefore we do //DEPREC /// not update it when adding the joint in the kinematic chain. //DEPREC void addChildJoint (JointPtr_t joint, //DEPREC bool computePositionInParent = true); /// Number of child joints std::size_t numberChildJoints () const; /// Get child joint JointPtr_t childJoint (std::size_t rank) const; /// Get (constant) placement of joint in parent frame, i.e. model.jointPlacement[idx] const Transform3f& positionInParentFrame () const; //DEPREC /// Set position of joint in parent frame //DEPREC void positionInParentFrame (const Transform3f& p); ///\} // ----------------------------------------------------------------------- /// \name Bounds /// \{ //DEPREC /// Set whether given degree of freedom is bounded //DEPREC void isBounded (size_type rank, bool bounded); //DEPREC /// Get whether given degree of freedom is bounded //DEPREC bool isBounded (size_type rank) const; //DEPREC /// Get lower bound of given degree of freedom //DEPREC value_type lowerBound (size_type rank) const; //DEPREC /// Get upper bound of given degree of freedom //DEPREC value_type upperBound (size_type rank) const; //DEPREC /// Set lower bound of given degree of freedom //DEPREC void lowerBound (size_type rank, value_type lowerBound); //DEPREC /// Set upper bound of given degree of freedom //DEPREC void upperBound (size_type rank, value_type upperBound); /// Get upper bound on linear velocity of the joint frame /// \return coefficient \f$\lambda\f$ such that /// \f{equation*} /// \forall \mathbf{q}_{joint}\ \ \ \ \ \ \|\mathbf {v}\| \leq \lambda \|\mathbf{\dot{q}}_{joint}\| /// \f} /// where /// \li \f$\mathbf{q}_{joint}\f$ is any joint configuration, /// \li \f$\mathbf{\dot{q}}_{joint}\f$ is the joint velocity, and /// \li \f$\mathbf{v} = J(\mathbf{q})*\mathbf{\dot{q}} \f$ is the linear velocity of the joint frame. //NOTYET value_type upperBoundLinearVelocity () const; /// Get upper bound on angular velocity of the joint frame /// \return coefficient \f$\lambda\f$ such that /// \f{equation*} /// \forall \mathbf{q}_{joint}\ \ \ \ \ \ \|\omega\| \leq \lambda \|\mathbf{\dot{q}}_{joint}\| /// \f} /// where /// \li \f$\mathbf{q}_{joint}\f$ is any joint configuration, /// \li \f$\mathbf{\dot{q}}_{joint}\f$ is the joint velocity, and /// \li \f$\omega = J(\mathbf{q})*\mathbf{\dot{q}}\f$ is the angular velocity of the joint frame. //NOTYET value_type upperBoundAngularVelocity () const; /// Maximal distance of joint origin to parent origin //NOTYET const value_type& maximalDistanceToParent () const; /// Compute the maximal distance. \sa maximalDistanceToParent //NOTYET void computeMaximalDistanceToParent (); /// \} // ----------------------------------------------------------------------- /// \name Jacobian /// \{ /// Get const reference to Jacobian /// \param localFrame if true, compute the jacobian (6d) in the local frame, /// whose linear part corresponds to the velocity of the center of the frame. /// If false, the jacobian is expressed in the global frame and its linear part /// corresponds to the value of the velocity vector field at the center of the world. const JointJacobian_t& jacobian (const bool localFrame=true) const; /// Get non const reference to Jacobian /// \param localFrame if true, compute the jacobian (6d) in the local frame, /// whose linear part corresponds to the velocity of the center of the frame. /// If false, the jacobian is expressed in the global frame and its linear part /// corresponds to the value of the velocity vector field at the center of the world. JointJacobian_t& jacobian (const bool localFrame=true); /// \} // ----------------------------------------------------------------------- //DEPREC /// Access to configuration space //DEPREC JointConfiguration* configuration () const {return configuration_;} //DEPREC /// Set robot owning the kinematic chain //DEPREC void robot (const DeviceWkPtr_t& device) {robot_ = device;} /// Access robot owning the object DeviceConstPtr_t robot () const { selfAssert(); return devicePtr;} /// Access robot owning the object DevicePtr_t robot () { selfAssert(); return devicePtr;} /// \name Body linked to the joint /// \{ /// Get linked body BodyPtr_t linkedBody () const; //DEPREC /// Set linked body //DEPREC void setLinkedBody (const BodyPtr_t& body); /// \} //DEPREC /// \name Compatibility with urdf //DEPREC /// \{ //DEPREC /// Get urdf link position in joint frame //DEPREC /// //DEPREC /// When parsing urdf pinocchios, joint frames are reoriented in order //DEPREC /// to rotate about their x-axis. For some applications, it is necessary //DEPREC /// to be able to recover the position of the urdf link attached to //DEPREC /// the joint. //DEPREC const Transform3f& linkInJointFrame () const; //DEPREC /// Set urdf link position in joint frame //DEPREC void linkInJointFrame (const Transform3f& transform); //DEPREC /// Get link name //DEPREC const std::string& linkName () const; //DEPREC /// Set link name //DEPREC void linkName (const std::string& linkName) //DEPREC /// \} /// Display joint virtual std::ostream& display (std::ostream& os) const; protected: value_type maximalDistanceToParent_; vector_t neutralConfiguration_; DevicePtr_t devicePtr; mutable JointJacobian_t jacobian_; Index jointIndex; std::vector<Index> children; /// Store list of childrens. void setChildList(); ModelPtr_t model() ; ModelConstPtr_t model() const ; DataPtr_t data() ; DataConstPtr_t data() const ; /// Assert that the members of the struct are valid (no null pointer, etc). void selfAssert() const; friend class Device; }; // class Joint inline std::ostream& operator<< (std::ostream& os, const Joint& joint) { return joint.display(os); } /** Fake std::vector<Joint>, used to comply with the actual structure of hpp::model. * * You can use it for the following loop: * for (JointVector_t::const_iterator it = jv.begin (); * it != jv.end (); ++it) * cout << (*it)->name; */ struct JointVector : public FakeContainer<JointPtr_t,JointConstPtr_t> { JointVector(DevicePtr_t device) : FakeContainer<JointPtr_t,JointConstPtr_t>(device) {} JointVector() {} virtual ~JointVector() {} virtual JointPtr_t at(const size_type i) ; virtual JointConstPtr_t at(const size_type i) const ; virtual size_type size() const ; virtual size_type iend() const ; void selfAssert(size_type i = 0) const; }; } // namespace pinocchio } // namespace hpp #endif // HPP_PINOCCHIO_JOINT_HH <commit_msg>Add Joint::index<commit_after>// // Copyright (c) 2016 CNRS // Author: NMansard from Florent Lamiraux // // // This file is part of hpp-pinocchio // hpp-pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_PINOCCHIO_JOINT_HH # define HPP_PINOCCHIO_JOINT_HH # include <cstddef> # include <hpp/fcl/math/transform.h> # include <hpp/pinocchio/config.hh> # include <hpp/pinocchio/fwd.hh> # include <hpp/pinocchio/fake-container.hh> namespace hpp { namespace pinocchio { /// Robot joint /// /// A joint maps an input vector to a transformation of SE(3) from the /// parent frame to the joint frame. /// /// The input vector is provided through the configuration vector of the /// robot the joint belongs to. The joint input vector is composed of the /// components of the robot configuration starting at /// Joint::rankInConfiguration. /// /// The joint input vector represents a element of a Lie group, either /// \li a vector space for JointTranslation, and bounded JointRotation, /// \li the unit circle for non-bounded JointRotation joints, /// \li an element of SO(3) for JointSO3, represented by a unit quaternion. /// /// Operations specific to joints (uniform sampling of input space, straight /// interpolation, distance, ...) are performed by a JointConfiguration /// instance that has the same class hierarchy as Joint. class HPP_PINOCCHIO_DLLAPI Joint { public: typedef se3::Index Index; /// \name Construction and copy and destruction /// \{ /// Constructor /// \param device pointer on the device the joint is belonging to. /// \param indexInJointList index of the joint, i.e. joint = device.model.joints[index] Joint (DevicePtr_t device, Index indexInJointList ); //DEPREC /// Constructor //DEPREC /// \param initialPosition position of the joint before being inserted //DEPREC /// in a kinematic chain, //DEPREC /// \param configSize dimension of the configuration vector, //DEPREC /// \param numberDof dimension of the velocity vector. //DEPREC Joint (const Transform3f& initialPosition, size_type configSize, //DEPREC size_type numberDof); //DEPREC /// Copy constructor //DEPREC /// //DEPREC /// Clone body and therefore inner and outer objects (see Body::clone). //DEPREC Joint (const Joint& joint); //DEPREC /// Return pointer to copy of this //DEPREC /// //DEPREC /// Clone body and therefore inner and outer objects (see Body::clone). //DEPREC virtual JointPtr_t clone () const = 0; //DEPREC virtual ~Joint (); ~Joint() {} /// \} // ----------------------------------------------------------------------- /// \name Name /// \{ //DEPREC /// Set name //DEPREC virtual inline void name(const std::string& name) /// Get name const std::string& name() const; /// \} // ----------------------------------------------------------------------- /// \name Position /// \{ //DEPREC /// Joint initial position (when robot is in zero configuration) //DEPREC const Transform3f& initialPosition () const; /// Joint transformation const Transform3f& currentTransformation () const; //DEPREC /// Compute position of joint //DEPREC /// \param configuration the configuration of the robot, //DEPREC /// \param parentPosition position of parent joint, //DEPREC /// \retval position position of this joint. //DEPREC virtual void computePosition (ConfigurationIn_t configuration, //DEPREC const Transform3f& parentPosition, //DEPREC Transform3f& position) const = 0; //DEPREC /// Compute position of this joint and all its descendents. //DEPREC void recursiveComputePosition (ConfigurationIn_t configuration, //DEPREC const Transform3f& parentPosition) const; //DEPREC /// Compute jacobian matrix of joint and all its descendents. //DEPREC void computeJacobian (); /// Get neutral configuration of joint //NOTYET vector_t neutralConfiguration () const; ///\} // ----------------------------------------------------------------------- /// \name Size and rank ///\} /// Return number of degrees of freedom size_type numberDof () const; /// Return number of degrees of freedom size_type configSize () const; /// Return rank of the joint in the configuration vector size_type rankInConfiguration () const; /// Return rank of the joint in the velocity vector size_type rankInVelocity () const; ///\} // ----------------------------------------------------------------------- /// \name Kinematic chain /// \{ /// Get a pointer to the parent joint (if any). // DEPREC JointPtr_t parentJoint () const //DEPREC /// Add child joint //DEPREC /// \param joint child joint added to this one, //DEPREC /// \param computePositionInParent whether to compute position of the //DEPREC /// child joint in this one's frame. //DEPREC /// //DEPREC /// \note When building a kinematic chain, we usually build the //DEPREC /// joint in its initial position and compute the (constant) //DEPREC /// position of the joint in its parent when adding the joint in //DEPREC /// the kinematic chain. When copying a kinematic chain, we copy the //DEPREC /// position of the joint in its parent frame and therefore we do //DEPREC /// not update it when adding the joint in the kinematic chain. //DEPREC void addChildJoint (JointPtr_t joint, //DEPREC bool computePositionInParent = true); /// Number of child joints std::size_t numberChildJoints () const; /// Get child joint JointPtr_t childJoint (std::size_t rank) const; /// Get (constant) placement of joint in parent frame, i.e. model.jointPlacement[idx] const Transform3f& positionInParentFrame () const; //DEPREC /// Set position of joint in parent frame //DEPREC void positionInParentFrame (const Transform3f& p); ///\} // ----------------------------------------------------------------------- /// \name Bounds /// \{ //DEPREC /// Set whether given degree of freedom is bounded //DEPREC void isBounded (size_type rank, bool bounded); //DEPREC /// Get whether given degree of freedom is bounded //DEPREC bool isBounded (size_type rank) const; //DEPREC /// Get lower bound of given degree of freedom //DEPREC value_type lowerBound (size_type rank) const; //DEPREC /// Get upper bound of given degree of freedom //DEPREC value_type upperBound (size_type rank) const; //DEPREC /// Set lower bound of given degree of freedom //DEPREC void lowerBound (size_type rank, value_type lowerBound); //DEPREC /// Set upper bound of given degree of freedom //DEPREC void upperBound (size_type rank, value_type upperBound); /// Get upper bound on linear velocity of the joint frame /// \return coefficient \f$\lambda\f$ such that /// \f{equation*} /// \forall \mathbf{q}_{joint}\ \ \ \ \ \ \|\mathbf {v}\| \leq \lambda \|\mathbf{\dot{q}}_{joint}\| /// \f} /// where /// \li \f$\mathbf{q}_{joint}\f$ is any joint configuration, /// \li \f$\mathbf{\dot{q}}_{joint}\f$ is the joint velocity, and /// \li \f$\mathbf{v} = J(\mathbf{q})*\mathbf{\dot{q}} \f$ is the linear velocity of the joint frame. //NOTYET value_type upperBoundLinearVelocity () const; /// Get upper bound on angular velocity of the joint frame /// \return coefficient \f$\lambda\f$ such that /// \f{equation*} /// \forall \mathbf{q}_{joint}\ \ \ \ \ \ \|\omega\| \leq \lambda \|\mathbf{\dot{q}}_{joint}\| /// \f} /// where /// \li \f$\mathbf{q}_{joint}\f$ is any joint configuration, /// \li \f$\mathbf{\dot{q}}_{joint}\f$ is the joint velocity, and /// \li \f$\omega = J(\mathbf{q})*\mathbf{\dot{q}}\f$ is the angular velocity of the joint frame. //NOTYET value_type upperBoundAngularVelocity () const; /// Maximal distance of joint origin to parent origin //NOTYET const value_type& maximalDistanceToParent () const; /// Compute the maximal distance. \sa maximalDistanceToParent //NOTYET void computeMaximalDistanceToParent (); /// \} // ----------------------------------------------------------------------- /// \name Jacobian /// \{ /// Get const reference to Jacobian /// \param localFrame if true, compute the jacobian (6d) in the local frame, /// whose linear part corresponds to the velocity of the center of the frame. /// If false, the jacobian is expressed in the global frame and its linear part /// corresponds to the value of the velocity vector field at the center of the world. const JointJacobian_t& jacobian (const bool localFrame=true) const; /// Get non const reference to Jacobian /// \param localFrame if true, compute the jacobian (6d) in the local frame, /// whose linear part corresponds to the velocity of the center of the frame. /// If false, the jacobian is expressed in the global frame and its linear part /// corresponds to the value of the velocity vector field at the center of the world. JointJacobian_t& jacobian (const bool localFrame=true); /// \} // ----------------------------------------------------------------------- //DEPREC /// Access to configuration space //DEPREC JointConfiguration* configuration () const {return configuration_;} //DEPREC /// Set robot owning the kinematic chain //DEPREC void robot (const DeviceWkPtr_t& device) {robot_ = device;} /// Access robot owning the object DeviceConstPtr_t robot () const { selfAssert(); return devicePtr;} /// Access robot owning the object DevicePtr_t robot () { selfAssert(); return devicePtr;} /// \name Body linked to the joint /// \{ /// Get linked body BodyPtr_t linkedBody () const; //DEPREC /// Set linked body //DEPREC void setLinkedBody (const BodyPtr_t& body); /// \} //DEPREC /// \name Compatibility with urdf //DEPREC /// \{ //DEPREC /// Get urdf link position in joint frame //DEPREC /// //DEPREC /// When parsing urdf pinocchios, joint frames are reoriented in order //DEPREC /// to rotate about their x-axis. For some applications, it is necessary //DEPREC /// to be able to recover the position of the urdf link attached to //DEPREC /// the joint. //DEPREC const Transform3f& linkInJointFrame () const; //DEPREC /// Set urdf link position in joint frame //DEPREC void linkInJointFrame (const Transform3f& transform); //DEPREC /// Get link name //DEPREC const std::string& linkName () const; //DEPREC /// Set link name //DEPREC void linkName (const std::string& linkName) //DEPREC /// \} /// Display joint virtual std::ostream& display (std::ostream& os) const; /// \name Pinocchio API /// \{ const Index& index () const { return jointIndex; } /// \} protected: value_type maximalDistanceToParent_; vector_t neutralConfiguration_; DevicePtr_t devicePtr; mutable JointJacobian_t jacobian_; Index jointIndex; std::vector<Index> children; /// Store list of childrens. void setChildList(); ModelPtr_t model() ; ModelConstPtr_t model() const ; DataPtr_t data() ; DataConstPtr_t data() const ; /// Assert that the members of the struct are valid (no null pointer, etc). void selfAssert() const; friend class Device; }; // class Joint inline std::ostream& operator<< (std::ostream& os, const Joint& joint) { return joint.display(os); } /** Fake std::vector<Joint>, used to comply with the actual structure of hpp::model. * * You can use it for the following loop: * for (JointVector_t::const_iterator it = jv.begin (); * it != jv.end (); ++it) * cout << (*it)->name; */ struct JointVector : public FakeContainer<JointPtr_t,JointConstPtr_t> { JointVector(DevicePtr_t device) : FakeContainer<JointPtr_t,JointConstPtr_t>(device) {} JointVector() {} virtual ~JointVector() {} virtual JointPtr_t at(const size_type i) ; virtual JointConstPtr_t at(const size_type i) const ; virtual size_type size() const ; virtual size_type iend() const ; void selfAssert(size_type i = 0) const; }; } // namespace pinocchio } // namespace hpp #endif // HPP_PINOCCHIO_JOINT_HH <|endoftext|>
<commit_before>/** * @file iutility.cpp * @brief utility interface class * @author Byunghun Hwang<[email protected]> * @date 2015. 9. 6 * @details utility interface class */ #ifndef _COSSB_IUTILITY_HPP_ #define _COSSB_IUTILITY_HPP_ #include <sys/stat.h> namespace cossb { namespace interface { class iutility { public: iutility() { } virtual ~iutility() { } /** * @brief launch interface function * @details pass all arguments to launch interface, inherited class should control the arguments */ virtual bool execute(int argc, char* argv[]) = 0; protected: bool exist(const char* utility) { struct stat buf; return (stat(utility, &buf)==0); } }; } /* namespace interfce */ } /* namespace ossb */ #endif /* _COSSB_IUTILITY_HPP_ */ <commit_msg>change interface function<commit_after>/** * @file iutility.cpp * @brief utility interface class * @author Byunghun Hwang<[email protected]> * @date 2015. 9. 6 * @details utility interface class */ #ifndef _COSSB_IUTILITY_HPP_ #define _COSSB_IUTILITY_HPP_ #include <sys/stat.h> namespace cossb { namespace interface { class iutility { public: iutility() { } virtual ~iutility() { } /** * @brief launch interface function * @details pass all arguments to launch interface, inherited class should control the arguments */ virtual bool execute(int argc, char* argv[]) = 0; protected: bool exist(const char* utility) { struct stat buf; return (stat(utility, &buf)==0); } }; } /* namespace interfce */ } /* namespace cossb */ #endif /* _COSSB_IUTILITY_HPP_ */ <|endoftext|>
<commit_before>#pragma once #include <atomic> #include <string> #include <vector> #include <memory> #include <glm/glm.hpp> #include <mos/gfx/texture.hpp> namespace mos::gfx { class Texture_2D; using Shared_texture_2D = std::shared_ptr<Texture_2D>; /** Texture in two dimension. Contains chars as data. */ class Texture_2D final : public Texture { public: template <class T> Texture_2D(T begin, T end, int width, int height, const gli::format &format = gli::format::FORMAT_RGBA8_SRGB_PACK8, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat, const bool mipmaps = true) : Texture(filter, wrap, mipmaps) { std::memcpy(texture_.data(), begin, std::distance(begin, end)); modified = std::chrono::system_clock::now(); } Texture_2D(int width, int height, const gli::format &format = gli::format::FORMAT_RGBA8_SRGB_PACK8, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat, bool mipmaps = true); /** Load from file */ static Shared_texture_2D load(const std::string &path, bool color_data = true, bool mipmaps = true, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat); /** Create from file. */ Texture_2D(const std::string &path, bool color_data = true, bool mipmaps = true, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat); auto width() const -> int; auto height() const -> int; const void *data() const; gli::format format() const; gli::swizzles swizzles() const; private: gli::texture2d texture_; }; } <commit_msg>Refactor<commit_after>#pragma once #include <atomic> #include <string> #include <vector> #include <memory> #include <glm/glm.hpp> #include <mos/gfx/texture.hpp> namespace mos::gfx { class Texture_2D; using Shared_texture_2D = std::shared_ptr<Texture_2D>; /** Texture in two dimension. Contains chars as data. */ class Texture_2D final : public Texture { public: template <class T> Texture_2D(T begin, T end, int width, int height, const gli::format &format = gli::format::FORMAT_RGBA8_SRGB_PACK8, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat, const bool mipmaps = true) : Texture(filter, wrap, mipmaps) { std::memcpy(texture_.data(), begin, std::distance(begin, end)); } Texture_2D(int width, int height, const gli::format &format = gli::format::FORMAT_RGBA8_SRGB_PACK8, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat, bool mipmaps = true); /** Load from file */ static Shared_texture_2D load(const std::string &path, bool color_data = true, bool mipmaps = true, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat); /** Create from file. */ Texture_2D(const std::string &path, bool color_data = true, bool generate_mipmaps = true, const Filter &filter = Filter::Linear, const Wrap &wrap = Wrap::Repeat); auto width() const -> int; auto height() const -> int; const void *data() const; gli::format format() const; gli::swizzles swizzles() const; private: gli::texture2d texture_; }; } <|endoftext|>
<commit_before>#pragma once #include <utility> #include <type_traits> #include "any.hpp" #include "meta/type_list.hpp" #include "meta/free_function_deduction.hpp" namespace shadow { typedef any (*free_function_binding_signature)(any*); //////////////////////////////////////////////////////////////////////////////// // generic bind point for free functions // has the same signature as function pointer free_function_binding_signature // which can be stored in the free_function_info struct namespace free_function_detail { // necessary to handle void as return type differently when calling underlying // free function template <class ReturnType> struct return_type_specializer { // dispatch: unpacks argument type list and sequence to correctly index into // argument array and call get with the right types to retrieve raw values // from the anys template <class FunctionPointerType, FunctionPointerType FunctionPointerValue, class... ArgTypes, std::size_t... ArgSeq> static any dispatch(any* argument_array, t_list::type_list<ArgTypes...>, std::index_sequence<ArgSeq...>) { // necessary to remove reference from types as any only stores // unqualified types, ie values only return FunctionPointerValue( argument_array[ArgSeq] .get<typename std::remove_reference_t<ArgTypes>>()...); } }; template <> struct return_type_specializer<void> { // dispatch: unpacks argument type list and sequence to correctly index into // argument array and call get with the right types to retrieve raw values // from the anys template <class FunctionPointerType, FunctionPointerType FunctionPointerValue, class... ArgTypes, std::size_t... ArgSeq> static any dispatch(any* argument_array, t_list::type_list<ArgTypes...>, std::index_sequence<ArgSeq...>) { // necessary to remove reference from types as any only stores // unqualified types, ie values only FunctionPointerValue( argument_array[ArgSeq] .get<typename std::remove_reference_t<ArgTypes>>()...); // return empty any, ie 'void' return any(); } }; // the value of the function pointer is stored at runtime in the template // overload set // this enables any function to be wrapped into uniform function signature that // can be stored homogenously at runtime template <class FunctionPointerType, FunctionPointerType FunctionPointerValue> any generic_free_function_bind_point(any* argument_array) { typedef free_function_return_type_t<FunctionPointerType> return_type; typedef free_function_parameter_types_t<FunctionPointerType> parameter_types; // make integer sequence from type list typedef t_list::integer_sequence_from_type_list_t<parameter_types> parameter_sequence; return return_type_specializer<return_type>:: template dispatch<FunctionPointerType, FunctionPointerValue>( argument_array, parameter_types(), parameter_sequence()); } } } <commit_msg>Add typedef for member function binding point signature. modified: include/reflection_binding.hpp<commit_after>#pragma once #include <utility> #include <type_traits> #include "any.hpp" #include "meta/type_list.hpp" #include "meta/free_function_deduction.hpp" namespace shadow { typedef any (*free_function_binding_signature)(any*); typedef any (*member_function_binding_signature)(any&, any*); //////////////////////////////////////////////////////////////////////////////// // generic bind point for free functions // has the same signature as function pointer free_function_binding_signature // which can be stored in the free_function_info struct namespace free_function_detail { // necessary to handle void as return type differently when calling underlying // free function template <class ReturnType> struct return_type_specializer { // dispatch: unpacks argument type list and sequence to correctly index into // argument array and call get with the right types to retrieve raw values // from the anys template <class FunctionPointerType, FunctionPointerType FunctionPointerValue, class... ArgTypes, std::size_t... ArgSeq> static any dispatch(any* argument_array, t_list::type_list<ArgTypes...>, std::index_sequence<ArgSeq...>) { // necessary to remove reference from types as any only stores // unqualified types, ie values only return FunctionPointerValue( argument_array[ArgSeq] .get<typename std::remove_reference_t<ArgTypes>>()...); } }; template <> struct return_type_specializer<void> { // dispatch: unpacks argument type list and sequence to correctly index into // argument array and call get with the right types to retrieve raw values // from the anys template <class FunctionPointerType, FunctionPointerType FunctionPointerValue, class... ArgTypes, std::size_t... ArgSeq> static any dispatch(any* argument_array, t_list::type_list<ArgTypes...>, std::index_sequence<ArgSeq...>) { // necessary to remove reference from types as any only stores // unqualified types, ie values only FunctionPointerValue( argument_array[ArgSeq] .get<typename std::remove_reference_t<ArgTypes>>()...); // return empty any, ie 'void' return any(); } }; // the value of the function pointer is stored at runtime in the template // overload set // this enables any function to be wrapped into uniform function signature that // can be stored homogenously at runtime template <class FunctionPointerType, FunctionPointerType FunctionPointerValue> any generic_free_function_bind_point(any* argument_array) { typedef free_function_return_type_t<FunctionPointerType> return_type; typedef free_function_parameter_types_t<FunctionPointerType> parameter_types; // make integer sequence from type list typedef t_list::integer_sequence_from_type_list_t<parameter_types> parameter_sequence; return return_type_specializer<return_type>:: template dispatch<FunctionPointerType, FunctionPointerValue>( argument_array, parameter_types(), parameter_sequence()); } } } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <memory> #include <valijson/constraints/constraint.hpp> #include <valijson/internal/optional.hpp> #include <valijson/exceptions.hpp> namespace valijson { /** * Represents a sub-schema within a JSON Schema * * While all JSON Schemas have at least one sub-schema, the root, some will * have additional sub-schemas that are defined as part of constraints that are * included in the schema. For example, a 'oneOf' constraint maintains a set of * references to one or more nested sub-schemas. As per the definition of a * oneOf constraint, a document is valid within that constraint if it validates * against one of the nested sub-schemas. */ class Subschema { public: /// Typedef for custom new-/malloc-like function typedef void * (*CustomAlloc)(size_t size); /// Typedef for custom free-like function typedef void (*CustomFree)(void *); /// Typedef the Constraint class into the local namespace for convenience typedef constraints::Constraint Constraint; /// Typedef for a function that can be applied to each of the Constraint /// instances owned by a Schema. typedef std::function<bool (const Constraint &)> ApplyFunction; // Disable copy construction Subschema(const Subschema &) = delete; // Disable copy assignment Subschema & operator=(const Subschema &) = delete; /** * @brief Construct a new Subschema object */ Subschema() : m_allocFn(::operator new) , m_freeFn(::operator delete) , m_alwaysInvalid(false) { } /** * @brief Construct a new Subschema using custom memory management * functions * * @param allocFn malloc- or new-like function to allocate memory * within Schema, such as for Subschema instances * @param freeFn free-like function to free memory allocated with * the `customAlloc` function */ Subschema(CustomAlloc allocFn, CustomFree freeFn) : m_allocFn(allocFn) , m_freeFn(freeFn) , m_alwaysInvalid(false) { // explicitly initialise optionals. See: https://github.com/tristanpenman/valijson/issues/124 m_description = opt::nullopt; m_id = opt::nullopt; m_title = opt::nullopt; } /** * @brief Clean up and free all memory managed by the Subschema */ virtual ~Subschema() { #if VALIJSON_USE_EXCEPTIONS try { #endif for (auto constConstraint : m_constraints) { auto *constraint = const_cast<Constraint *>(constConstraint); constraint->~Constraint(); m_freeFn(constraint); } m_constraints.clear(); #if VALIJSON_USE_EXCEPTIONS } catch (const std::exception &e) { fprintf(stderr, "Caught an exception in Subschema destructor: %s", e.what()); } #endif } /** * @brief Add a constraint to this sub-schema * * The constraint will be copied before being added to the list of * constraints for this Subschema. Note that constraints will be copied * only as deep as references to other Subschemas - e.g. copies of * constraints that refer to sub-schemas, will continue to refer to the * same Subschema instances. * * @param constraint Reference to the constraint to copy */ void addConstraint(const Constraint &constraint) { Constraint *newConstraint = constraint.clone(m_allocFn, m_freeFn); #if VALIJSON_USE_EXCEPTIONS try { #endif m_constraints.push_back(newConstraint); #if VALIJSON_USE_EXCEPTIONS } catch (...) { newConstraint->~Constraint(); m_freeFn(newConstraint); throw; } #endif } /** * @brief Invoke a function on each child Constraint * * This function will apply the callback function to each constraint in * the Subschema, even if one of the invocations returns \c false. However, * if one or more invocations of the callback function return \c false, * this function will also return \c false. * * @returns \c true if all invocations of the callback function are * successful, \c false otherwise */ bool apply(ApplyFunction &applyFunction) const { bool allTrue = true; for (const Constraint *constraint : m_constraints) { allTrue = applyFunction(*constraint) && allTrue; } return allTrue; } /** * @brief Invoke a function on each child Constraint * * This is a stricter version of the apply() function that will return * immediately if any of the invocations of the callback function return * \c false. * * @returns \c true if all invocations of the callback function are * successful, \c false otherwise */ bool applyStrict(ApplyFunction &applyFunction) const { for (const Constraint *constraint : m_constraints) { if (!applyFunction(*constraint)) { return false; } } return true; } bool getAlwaysInvalid() const { return m_alwaysInvalid; } /** * @brief Get the description associated with this sub-schema * * @throws std::runtime_error if a description has not been set * * @returns string containing sub-schema description */ std::string getDescription() const { if (m_description) { return *m_description; } throwRuntimeError("Schema does not have a description"); } /** * @brief Get the ID associated with this sub-schema * * @throws std::runtime_error if an ID has not been set * * @returns string containing sub-schema ID */ std::string getId() const { if (m_id) { return *m_id; } throwRuntimeError("Schema does not have an ID"); } /** * @brief Get the title associated with this sub-schema * * @throws std::runtime_error if a title has not been set * * @returns string containing sub-schema title */ std::string getTitle() const { if (m_title) { return *m_title; } throwRuntimeError("Schema does not have a title"); } /** * @brief Check whether this sub-schema has a description * * @return boolean value */ bool hasDescription() const { return static_cast<bool>(m_description); } /** * @brief Check whether this sub-schema has an ID * * @return boolean value */ bool hasId() const { return static_cast<bool>(m_id); } /** * @brief Check whether this sub-schema has a title * * @return boolean value */ bool hasTitle() const { return static_cast<bool>(m_title); } void setAlwaysInvalid(bool value) { m_alwaysInvalid = value; } /** * @brief Set the description for this sub-schema * * The description will not be used for validation, but may be used as part * of the user interface for interacting with schemas and sub-schemas. As * an example, it may be used as part of the validation error descriptions * that are produced by the Validator and ValidationVisitor classes. * * @param description new description */ void setDescription(const std::string &description) { m_description = description; } void setId(const std::string &id) { m_id = id; } /** * @brief Set the title for this sub-schema * * The title will not be used for validation, but may be used as part * of the user interface for interacting with schemas and sub-schema. As an * example, it may be used as part of the validation error descriptions * that are produced by the Validator and ValidationVisitor classes. * * @param title new title */ void setTitle(const std::string &title) { m_title = title; } protected: CustomAlloc m_allocFn; CustomFree m_freeFn; private: bool m_alwaysInvalid; /// List of pointers to constraints that apply to this schema. std::vector<const Constraint *> m_constraints; /// Schema description (optional) opt::optional<std::string> m_description; /// Id to apply when resolving the schema URI opt::optional<std::string> m_id; /// Title string associated with the schema (optional) opt::optional<std::string> m_title; }; } // namespace valijson <commit_msg>Add missing include<commit_after>#pragma once #include <functional> #include <memory> #include <vector> #include <valijson/constraints/constraint.hpp> #include <valijson/internal/optional.hpp> #include <valijson/exceptions.hpp> namespace valijson { /** * Represents a sub-schema within a JSON Schema * * While all JSON Schemas have at least one sub-schema, the root, some will * have additional sub-schemas that are defined as part of constraints that are * included in the schema. For example, a 'oneOf' constraint maintains a set of * references to one or more nested sub-schemas. As per the definition of a * oneOf constraint, a document is valid within that constraint if it validates * against one of the nested sub-schemas. */ class Subschema { public: /// Typedef for custom new-/malloc-like function typedef void * (*CustomAlloc)(size_t size); /// Typedef for custom free-like function typedef void (*CustomFree)(void *); /// Typedef the Constraint class into the local namespace for convenience typedef constraints::Constraint Constraint; /// Typedef for a function that can be applied to each of the Constraint /// instances owned by a Schema. typedef std::function<bool (const Constraint &)> ApplyFunction; // Disable copy construction Subschema(const Subschema &) = delete; // Disable copy assignment Subschema & operator=(const Subschema &) = delete; /** * @brief Construct a new Subschema object */ Subschema() : m_allocFn(::operator new) , m_freeFn(::operator delete) , m_alwaysInvalid(false) { } /** * @brief Construct a new Subschema using custom memory management * functions * * @param allocFn malloc- or new-like function to allocate memory * within Schema, such as for Subschema instances * @param freeFn free-like function to free memory allocated with * the `customAlloc` function */ Subschema(CustomAlloc allocFn, CustomFree freeFn) : m_allocFn(allocFn) , m_freeFn(freeFn) , m_alwaysInvalid(false) { // explicitly initialise optionals. See: https://github.com/tristanpenman/valijson/issues/124 m_description = opt::nullopt; m_id = opt::nullopt; m_title = opt::nullopt; } /** * @brief Clean up and free all memory managed by the Subschema */ virtual ~Subschema() { #if VALIJSON_USE_EXCEPTIONS try { #endif for (auto constConstraint : m_constraints) { auto *constraint = const_cast<Constraint *>(constConstraint); constraint->~Constraint(); m_freeFn(constraint); } m_constraints.clear(); #if VALIJSON_USE_EXCEPTIONS } catch (const std::exception &e) { fprintf(stderr, "Caught an exception in Subschema destructor: %s", e.what()); } #endif } /** * @brief Add a constraint to this sub-schema * * The constraint will be copied before being added to the list of * constraints for this Subschema. Note that constraints will be copied * only as deep as references to other Subschemas - e.g. copies of * constraints that refer to sub-schemas, will continue to refer to the * same Subschema instances. * * @param constraint Reference to the constraint to copy */ void addConstraint(const Constraint &constraint) { Constraint *newConstraint = constraint.clone(m_allocFn, m_freeFn); #if VALIJSON_USE_EXCEPTIONS try { #endif m_constraints.push_back(newConstraint); #if VALIJSON_USE_EXCEPTIONS } catch (...) { newConstraint->~Constraint(); m_freeFn(newConstraint); throw; } #endif } /** * @brief Invoke a function on each child Constraint * * This function will apply the callback function to each constraint in * the Subschema, even if one of the invocations returns \c false. However, * if one or more invocations of the callback function return \c false, * this function will also return \c false. * * @returns \c true if all invocations of the callback function are * successful, \c false otherwise */ bool apply(ApplyFunction &applyFunction) const { bool allTrue = true; for (const Constraint *constraint : m_constraints) { allTrue = applyFunction(*constraint) && allTrue; } return allTrue; } /** * @brief Invoke a function on each child Constraint * * This is a stricter version of the apply() function that will return * immediately if any of the invocations of the callback function return * \c false. * * @returns \c true if all invocations of the callback function are * successful, \c false otherwise */ bool applyStrict(ApplyFunction &applyFunction) const { for (const Constraint *constraint : m_constraints) { if (!applyFunction(*constraint)) { return false; } } return true; } bool getAlwaysInvalid() const { return m_alwaysInvalid; } /** * @brief Get the description associated with this sub-schema * * @throws std::runtime_error if a description has not been set * * @returns string containing sub-schema description */ std::string getDescription() const { if (m_description) { return *m_description; } throwRuntimeError("Schema does not have a description"); } /** * @brief Get the ID associated with this sub-schema * * @throws std::runtime_error if an ID has not been set * * @returns string containing sub-schema ID */ std::string getId() const { if (m_id) { return *m_id; } throwRuntimeError("Schema does not have an ID"); } /** * @brief Get the title associated with this sub-schema * * @throws std::runtime_error if a title has not been set * * @returns string containing sub-schema title */ std::string getTitle() const { if (m_title) { return *m_title; } throwRuntimeError("Schema does not have a title"); } /** * @brief Check whether this sub-schema has a description * * @return boolean value */ bool hasDescription() const { return static_cast<bool>(m_description); } /** * @brief Check whether this sub-schema has an ID * * @return boolean value */ bool hasId() const { return static_cast<bool>(m_id); } /** * @brief Check whether this sub-schema has a title * * @return boolean value */ bool hasTitle() const { return static_cast<bool>(m_title); } void setAlwaysInvalid(bool value) { m_alwaysInvalid = value; } /** * @brief Set the description for this sub-schema * * The description will not be used for validation, but may be used as part * of the user interface for interacting with schemas and sub-schemas. As * an example, it may be used as part of the validation error descriptions * that are produced by the Validator and ValidationVisitor classes. * * @param description new description */ void setDescription(const std::string &description) { m_description = description; } void setId(const std::string &id) { m_id = id; } /** * @brief Set the title for this sub-schema * * The title will not be used for validation, but may be used as part * of the user interface for interacting with schemas and sub-schema. As an * example, it may be used as part of the validation error descriptions * that are produced by the Validator and ValidationVisitor classes. * * @param title new title */ void setTitle(const std::string &title) { m_title = title; } protected: CustomAlloc m_allocFn; CustomFree m_freeFn; private: bool m_alwaysInvalid; /// List of pointers to constraints that apply to this schema. std::vector<const Constraint *> m_constraints; /// Schema description (optional) opt::optional<std::string> m_description; /// Id to apply when resolving the schema URI opt::optional<std::string> m_id; /// Title string associated with the schema (optional) opt::optional<std::string> m_title; }; } // namespace valijson <|endoftext|>
<commit_before>// Time: O(n) // Space: O(n) class Solution { public: bool canCross(vector<int>& stones) { unordered_map<int, int> lookup; for (int i = 0; i < stones.size(); ++i) { lookup[stones[i]] = i; } vector<bool> dp(stones.size()); dp[0] = true; for (int i = 0; i < stones.size(); ++i) { if (dp[i]) { for (const auto& k : {i - 1, i, i + 1}) { const auto it = lookup.find(stones[i] + k); if (it != lookup.end()) { dp[it->second] = true; } } } } return dp.back(); } }; <commit_msg>Update frog-jump.cpp<commit_after>// Time: O(n) ~ O(n^2) // Space: O(n) class Solution { public: bool canCross(vector<int>& stones) { if (stones[1] != 1) { return false; } unordered_map<int, unordered_set<int>> lookup; for (const auto& s: stones) { lookup.emplace(s, {unordered_set<int>()}); } lookup[1].emplace(1); for (int i = 0; i + 1 < stones.size(); ++i) { for (const auto& j : lookup[stones[i]]) { for (const auto& k : {j - 1, j, j + 1}) { if (k > 0 && lookup.count(stones[i] + k)) { lookup[stones[i] + k].emplace(k); } } } } return !lookup[stones.back()].empty(); } }; <|endoftext|>
<commit_before>// Time: O(1), per operation // Space: O(k), k is the capacity of cache class LFUCache { public: LFUCache(int capacity) : capa_(capacity), size_(0) { } int get(int key) { if (!key_to_nodeit_.count(key)) { return -1; } auto new_node = *key_to_nodeit_[key]; auto& freq = std::get<FREQ>(new_node); freq_to_nodes_[freq].erase(key_to_nodeit_[key]); if (freq_to_nodes_[freq].empty()) { freq_to_nodes_.erase(freq); if (min_freq_ == freq) { ++min_freq_; } } ++freq; freq_to_nodes_[freq].emplace_back(move(new_node)); key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end()); return std::get<VAL>(*key_to_nodeit_[key]); } void put(int key, int value) { if (capa_ <= 0) { return; } if (get(key) != -1) { std::get<VAL>(*key_to_nodeit_[key]) = value; return; } if (size_ == capa_) { key_to_nodeit_.erase(std::get<KEY>(freq_to_nodes_[min_freq_].front())); freq_to_nodes_[min_freq_].pop_front(); if (freq_to_nodes_[min_freq_].empty()) { freq_to_nodes_.erase(min_freq_); } --size_; } min_freq_ = 1; freq_to_nodes_[min_freq_].emplace_back(key, value, min_freq_); key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end()); ++size_; } private: enum Data {KEY, VAL, FREQ}; int capa_; int size_; int min_freq_; unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_; // freq to list of {key, val, freq} unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_; // key to list iterator }; /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */ <commit_msg>Update lfu-cache.cpp<commit_after>// Time: O(1), per operation // Space: O(k), k is the capacity of cache class LFUCache { public: LFUCache(int capacity) : capa_(capacity), size_(0), min_freq_(0) { } int get(int key) { if (!key_to_nodeit_.count(key)) { return -1; } auto new_node = *key_to_nodeit_[key]; auto& freq = std::get<FREQ>(new_node); freq_to_nodes_[freq].erase(key_to_nodeit_[key]); if (freq_to_nodes_[freq].empty()) { freq_to_nodes_.erase(freq); if (min_freq_ == freq) { ++min_freq_; } } ++freq; freq_to_nodes_[freq].emplace_back(move(new_node)); key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end()); return std::get<VAL>(*key_to_nodeit_[key]); } void put(int key, int value) { if (capa_ <= 0) { return; } if (get(key) != -1) { std::get<VAL>(*key_to_nodeit_[key]) = value; return; } if (size_ == capa_) { key_to_nodeit_.erase(std::get<KEY>(freq_to_nodes_[min_freq_].front())); freq_to_nodes_[min_freq_].pop_front(); if (freq_to_nodes_[min_freq_].empty()) { freq_to_nodes_.erase(min_freq_); } --size_; } min_freq_ = 1; freq_to_nodes_[min_freq_].emplace_back(key, value, min_freq_); key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end()); ++size_; } private: enum Data {KEY, VAL, FREQ}; int capa_; int size_; int min_freq_; unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_; // freq to list of {key, val, freq} unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_; // key to list iterator }; /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */ <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include <string> namespace cu { /// Tells whether the @c txt string starts with the @c start string. template <std::size_t N> bool startsWith( const std::string & txt, const char (&start)[N] ) { // The actual length of the `start` string is N-1, because of the // terminating '\0' character. const auto startLength = N-1; if ( txt.size() < startLength ) return false; return std::equal( start, start + startLength, txt.begin() ); } /// Tells whether the @c txt string ends with the @c end string. template <std::size_t N> bool endsWith( const std::string & txt, const char (&end)[N] ) { // The actual length of the `end` string is N-1, because of the // terminating '\0' character. const auto endLength = N-1; if ( txt.size() < endLength ) return false; return std::equal( end, end + endLength, txt.end()- endLength ); } /// Tells whether the @c txt string ends with the @c end string. inline bool endsWith( const std::string & txt, const std::string & end ) { if ( txt.size() < end.size() ) return false; return std::equal( end.begin(), end.end(), txt.end() - end.size() ); } /// Removes whitespaces from the beginning and end of a string. inline std::string trim( const std::string & s ) { auto first = s.begin(); auto last = s.end(); while ( first < last && std::isspace( *first) ) ++first; while ( last > first && std::isspace( *std::prev(last) ) ) --last; // NOOP return { first, last }; } } // namespace cu <commit_msg>New: Added and implemented function replaceEndWith() for string manipulation.<commit_after>#pragma once #include <algorithm> #include <cassert> #include <string> namespace cu { /// Tells whether the @c txt string starts with the @c start string. template <std::size_t N> bool startsWith( const std::string & txt, const char (&start)[N] ) { // The actual length of the `start` string is N-1, because of the // terminating '\0' character. const auto startLength = N-1; if ( txt.size() < startLength ) return false; return std::equal( start, start + startLength, txt.begin() ); } /// Tells whether the @c txt string ends with the @c end string. template <std::size_t N> bool endsWith( const std::string & txt, const char (&end)[N] ) { // The actual length of the `end` string is N-1, because of the // terminating '\0' character. const auto endLength = N-1; if ( txt.size() < endLength ) return false; return std::equal( end, end + endLength, txt.end()- endLength ); } /// Tells whether the @c txt string ends with the @c end string. inline bool endsWith( const std::string & txt, const std::string & end ) { if ( txt.size() < end.size() ) return false; return std::equal( end.begin(), end.end(), txt.end() - end.size() ); } /// Removes whitespaces from the beginning and end of a string. inline std::string trim( const std::string & s ) { auto first = s.begin(); auto last = s.end(); while ( first < last && std::isspace( *first) ) ++first; while ( last > first && std::isspace( *std::prev(last) ) ) --last; // NOOP return { first, last }; } inline std::string replaceEndWith( std::string input, const std::string & newEnd ) { assert( newEnd.size() <= input.size() ); auto newEndStart = input.end()-newEnd.size(); while ( (*newEndStart & 0xC0 ) == 0x80 ) // care about unicode (UTF-8) --newEndStart; std::copy( newEnd.begin(), newEnd.end (), newEndStart ); input.resize( newEndStart + newEnd.size() - input.begin() ); return std::move( input ); } } // namespace cu <|endoftext|>
<commit_before>// See LICENSE file for copyright and license details. #include "core/v2i.hpp" #include <cassert> #include <cstdlib> #include <cmath> V2i::V2i(int x, int y) : mX(x), mY(y) { } V2i::V2i() : mX(0), mY(0) { } V2i::~V2i() { } int V2i::x() const { return mX; } int V2i::y() const { return mY; } void V2i::setX(int x) { mX = x; } void V2i::setY(int y) { mY = y; } int V2i::distance(const V2i &b) const { int ax = x() + y() / 2; int bx = b.x() + b.y() / 2; int dx = bx - ax; int dy = b.y() - y(); return (abs(dx) + abs(dy) + abs(dx - dy)) / 2; } bool V2i::operator==(const V2i& b) const { return x() == b.x() && y() == b.y(); } V2i V2i::operator-(const V2i& b) const { return V2i(x() - b.x(), y() - b.y()); } V2i V2i::operator+(const V2i& b) const { return V2i(x() + b.x(), y() + b.y()); } int V2i::distance(const V2i& a, const V2i &b) { return a.distance(b); } <commit_msg>V2i: Removed empty line<commit_after>// See LICENSE file for copyright and license details. #include "core/v2i.hpp" #include <cassert> #include <cstdlib> #include <cmath> V2i::V2i(int x, int y) : mX(x), mY(y) { } V2i::V2i() : mX(0), mY(0) { } V2i::~V2i() { } int V2i::x() const { return mX; } int V2i::y() const { return mY; } void V2i::setX(int x) { mX = x; } void V2i::setY(int y) { mY = y; } int V2i::distance(const V2i &b) const { int ax = x() + y() / 2; int bx = b.x() + b.y() / 2; int dx = bx - ax; int dy = b.y() - y(); return (abs(dx) + abs(dy) + abs(dx - dy)) / 2; } bool V2i::operator==(const V2i& b) const { return x() == b.x() && y() == b.y(); } V2i V2i::operator-(const V2i& b) const { return V2i(x() - b.x(), y() - b.y()); } V2i V2i::operator+(const V2i& b) const { return V2i(x() + b.x(), y() + b.y()); } int V2i::distance(const V2i& a, const V2i &b) { return a.distance(b); } <|endoftext|>
<commit_before>/** * @file llchicletbar.cpp * @brief LLChicletBar class implementation * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // must be first include #include "llchicletbar.h" // library includes #include "llfloaterreg.h" #include "lllayoutstack.h" // newview includes #include "llchiclet.h" #include "llimfloater.h" // for LLIMFloater #include "llpaneltopinfobar.h" #include "llsyswellwindow.h" namespace { const std::string& PANEL_CHICLET_NAME = "chiclet_list_panel"; S32 get_curr_width(LLUICtrl* ctrl) { S32 cur_width = 0; if ( ctrl && ctrl->getVisible() ) { cur_width = ctrl->getRect().getWidth(); } return cur_width; } } LLChicletBar::LLChicletBar(const LLSD&) : mChicletPanel(NULL), mToolbarStack(NULL) { // IM floaters are from now managed by LLIMFloaterContainer. // See LLIMFloaterContainer::sessionVoiceOrIMStarted() and CHUI-125 // // Firstly add our self to IMSession observers, so we catch session events // // before chiclets do that. // LLIMMgr::getInstance()->addSessionObserver(this); buildFromFile("panel_chiclet_bar.xml"); } LLChicletBar::~LLChicletBar() { // IM floaters are from now managed by LLIMFloaterContainer. // See LLIMFloaterContainer::sessionVoiceOrIMStarted() and CHUI-125 // if (!LLSingleton<LLIMMgr>::destroyed()) // { // LLIMMgr::getInstance()->removeSessionObserver(this); // } } LLIMChiclet* LLChicletBar::createIMChiclet(const LLUUID& session_id) { LLIMChiclet::EType im_chiclet_type = LLIMChiclet::getIMSessionType(session_id); switch (im_chiclet_type) { case LLIMChiclet::TYPE_IM: return getChicletPanel()->createChiclet<LLIMP2PChiclet>(session_id); case LLIMChiclet::TYPE_GROUP: return getChicletPanel()->createChiclet<LLIMGroupChiclet>(session_id); case LLIMChiclet::TYPE_AD_HOC: return getChicletPanel()->createChiclet<LLAdHocChiclet>(session_id); case LLIMChiclet::TYPE_UNKNOWN: break; } return NULL; } //virtual void LLChicletBar::sessionAdded(const LLUUID& session_id, const std::string& name, const LLUUID& other_participant_id) { if (!getChicletPanel()) return; LLIMModel::LLIMSession* session = LLIMModel::getInstance()->findIMSession(session_id); if (!session) return; // no need to spawn chiclets for participants in P2P calls called through Avaline if (session->isP2P() && session->isOtherParticipantAvaline()) return; // Do not spawn chiclet when using the new multitab conversation UI if (LLIMConversation::isChatMultiTab()) { LLIMFloater::addToHost(session_id); return; } if (getChicletPanel()->findChiclet<LLChiclet>(session_id)) return; LLIMChiclet* chiclet = createIMChiclet(session_id); if(chiclet) { chiclet->setIMSessionName(name); chiclet->setOtherParticipantId(other_participant_id); LLIMFloater::onIMChicletCreated(session_id); } else { llwarns << "Could not create chiclet" << llendl; } } //virtual void LLChicletBar::sessionRemoved(const LLUUID& session_id) { if(getChicletPanel()) { // IM floater should be closed when session removed and associated chiclet closed LLIMFloater* im_floater = LLFloaterReg::findTypedInstance<LLIMFloater>("impanel", session_id); if (im_floater != NULL && !im_floater->getStartConferenceInSameFloater()) { // Close the IM floater only if we are not planning to close the P2P chat // and start a new conference in the same floater. im_floater->closeFloater(); } getChicletPanel()->removeChiclet(session_id); } } void LLChicletBar::sessionIDUpdated(const LLUUID& old_session_id, const LLUUID& new_session_id) { //this is only needed in case of outgoing ad-hoc/group chat sessions LLChicletPanel* chiclet_panel = getChicletPanel(); if (chiclet_panel) { //it should be ad-hoc im chiclet or group im chiclet LLChiclet* chiclet = chiclet_panel->findChiclet<LLChiclet>(old_session_id); if (chiclet) chiclet->setSessionId(new_session_id); } } S32 LLChicletBar::getTotalUnreadIMCount() { return getChicletPanel()->getTotalUnreadIMCount(); } BOOL LLChicletBar::postBuild() { mToolbarStack = getChild<LLLayoutStack>("toolbar_stack"); mChicletPanel = getChild<LLChicletPanel>("chiclet_list"); showWellButton("im_well", !LLIMWellWindow::getInstance()->isWindowEmpty()); showWellButton("notification_well", !LLNotificationWellWindow::getInstance()->isWindowEmpty()); LLPanelTopInfoBar::instance().setResizeCallback(boost::bind(&LLChicletBar::fitWithTopInfoBar, this)); LLPanelTopInfoBar::instance().setVisibleCallback(boost::bind(&LLChicletBar::fitWithTopInfoBar, this)); return TRUE; } void LLChicletBar::showWellButton(const std::string& well_name, bool visible) { LLView * panel = findChild<LLView>(well_name + "_panel"); if (!panel) return; panel->setVisible(visible); } void LLChicletBar::log(LLView* panel, const std::string& descr) { if (NULL == panel) return; LLView* layout = panel->getParent(); LL_DEBUGS("Chiclet Bar Rects") << descr << ": " << "panel: " << panel->getName() << ", rect: " << panel->getRect() << " layout: " << layout->getName() << ", rect: " << layout->getRect() << LL_ENDL; } void LLChicletBar::reshape(S32 width, S32 height, BOOL called_from_parent) { static S32 debug_calling_number = 0; lldebugs << "**************************************** " << ++debug_calling_number << llendl; S32 current_width = getRect().getWidth(); S32 delta_width = width - current_width; lldebugs << "Reshaping: " << ", width: " << width << ", cur width: " << current_width << ", delta_width: " << delta_width << ", called_from_parent: " << called_from_parent << llendl; if (mChicletPanel) log(mChicletPanel, "before"); // Difference between chiclet bar width required to fit its children and the actual width. (see EXT-991) // Positive value means that chiclet bar is not wide enough. // Negative value means that there is free space. static S32 extra_shrink_width = 0; bool should_be_reshaped = true; if (mChicletPanel && mToolbarStack) { // Firstly, update layout stack to ensure we deal with correct panel sizes. { // Force the updating of layout to reset panels collapse factor. mToolbarStack->updateLayout(); } // chiclet bar is narrowed if (delta_width < 0) { if (extra_shrink_width > 0) // not enough space { extra_shrink_width += llabs(delta_width); should_be_reshaped = false; } else { extra_shrink_width = processWidthDecreased(delta_width); // increase new width to extra_shrink_width value to not reshape less than chiclet bar minimum width += extra_shrink_width; } } // chiclet bar is widened else { if (extra_shrink_width > delta_width) { // Still not enough space. // Only subtract the delta from the required delta and don't reshape. extra_shrink_width -= delta_width; should_be_reshaped = false; } else if (extra_shrink_width > 0) { // If we have some extra shrink width let's reduce delta_width & width delta_width -= extra_shrink_width; width -= extra_shrink_width; extra_shrink_width = 0; } } } if (should_be_reshaped) { lldebugs << "Reshape all children with width: " << width << llendl; LLPanel::reshape(width, height, called_from_parent); } if (mChicletPanel) log(mChicletPanel, "after"); } S32 LLChicletBar::processWidthDecreased(S32 delta_width) { bool still_should_be_processed = true; const S32 chiclet_panel_shrink_headroom = getChicletPanelShrinkHeadroom(); // Decreasing width of chiclet panel. if (chiclet_panel_shrink_headroom > 0) { // we have some space to decrease chiclet panel S32 shrink_by = llmin(-delta_width, chiclet_panel_shrink_headroom); lldebugs << "delta_width: " << delta_width << ", panel_delta_min: " << chiclet_panel_shrink_headroom << ", shrink_by: " << shrink_by << llendl; // is chiclet panel wide enough to process resizing? delta_width += chiclet_panel_shrink_headroom; still_should_be_processed = delta_width < 0; lldebugs << "Shrinking chiclet panel by " << shrink_by << " px" << llendl; mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - shrink_by, mChicletPanel->getParent()->getRect().getHeight()); log(mChicletPanel, "after processing panel decreasing via chiclet panel"); lldebugs << "RS_CHICLET_PANEL" << ", delta_width: " << delta_width << llendl; } S32 extra_shrink_width = 0; if (still_should_be_processed) { extra_shrink_width = -delta_width; llwarns << "There is no enough width to reshape all children: " << extra_shrink_width << llendl; } return extra_shrink_width; } S32 LLChicletBar::getChicletPanelShrinkHeadroom() const { static const S32 min_width = mChicletPanel->getMinWidth(); const S32 cur_width = mChicletPanel->getParent()->getRect().getWidth(); S32 shrink_headroom = cur_width - min_width; llassert(shrink_headroom >= 0); // the panel cannot get narrower than the minimum return shrink_headroom; } void LLChicletBar::fitWithTopInfoBar() { LLPanelTopInfoBar& top_info_bar = LLPanelTopInfoBar::instance(); LLRect rect = getRect(); S32 width = rect.getWidth(); if (top_info_bar.getVisible()) { S32 delta = top_info_bar.calcScreenRect().mRight - calcScreenRect().mLeft; if (delta < 0 && rect.mLeft < llabs(delta)) delta = -rect.mLeft; rect.setLeftTopAndSize(rect.mLeft + delta, rect.mTop, rect.getWidth(), rect.getHeight()); width = rect.getWidth() - delta; } else { LLView* parent = getParent(); if (parent) { LLRect parent_rect = parent->getRect(); rect.setLeftTopAndSize(0, rect.mTop, rect.getWidth(), rect.getHeight()); width = parent_rect.getWidth(); } } setRect(rect); LLPanel::reshape(width, rect.getHeight(), false); } <commit_msg>CHUI-125 FIXED Supressed of a commented out code<commit_after>/** * @file llchicletbar.cpp * @brief LLChicletBar class implementation * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // must be first include #include "llchicletbar.h" // library includes #include "llfloaterreg.h" #include "lllayoutstack.h" // newview includes #include "llchiclet.h" #include "llimfloater.h" // for LLIMFloater #include "llpaneltopinfobar.h" #include "llsyswellwindow.h" namespace { const std::string& PANEL_CHICLET_NAME = "chiclet_list_panel"; S32 get_curr_width(LLUICtrl* ctrl) { S32 cur_width = 0; if ( ctrl && ctrl->getVisible() ) { cur_width = ctrl->getRect().getWidth(); } return cur_width; } } LLChicletBar::LLChicletBar(const LLSD&) : mChicletPanel(NULL), mToolbarStack(NULL) { buildFromFile("panel_chiclet_bar.xml"); } LLChicletBar::~LLChicletBar() { } LLIMChiclet* LLChicletBar::createIMChiclet(const LLUUID& session_id) { LLIMChiclet::EType im_chiclet_type = LLIMChiclet::getIMSessionType(session_id); switch (im_chiclet_type) { case LLIMChiclet::TYPE_IM: return getChicletPanel()->createChiclet<LLIMP2PChiclet>(session_id); case LLIMChiclet::TYPE_GROUP: return getChicletPanel()->createChiclet<LLIMGroupChiclet>(session_id); case LLIMChiclet::TYPE_AD_HOC: return getChicletPanel()->createChiclet<LLAdHocChiclet>(session_id); case LLIMChiclet::TYPE_UNKNOWN: break; } return NULL; } //virtual void LLChicletBar::sessionAdded(const LLUUID& session_id, const std::string& name, const LLUUID& other_participant_id) { if (!getChicletPanel()) return; LLIMModel::LLIMSession* session = LLIMModel::getInstance()->findIMSession(session_id); if (!session) return; // no need to spawn chiclets for participants in P2P calls called through Avaline if (session->isP2P() && session->isOtherParticipantAvaline()) return; // Do not spawn chiclet when using the new multitab conversation UI if (LLIMConversation::isChatMultiTab()) { LLIMFloater::addToHost(session_id); return; } if (getChicletPanel()->findChiclet<LLChiclet>(session_id)) return; LLIMChiclet* chiclet = createIMChiclet(session_id); if(chiclet) { chiclet->setIMSessionName(name); chiclet->setOtherParticipantId(other_participant_id); LLIMFloater::onIMChicletCreated(session_id); } else { llwarns << "Could not create chiclet" << llendl; } } //virtual void LLChicletBar::sessionRemoved(const LLUUID& session_id) { if(getChicletPanel()) { // IM floater should be closed when session removed and associated chiclet closed LLIMFloater* im_floater = LLFloaterReg::findTypedInstance<LLIMFloater>("impanel", session_id); if (im_floater != NULL && !im_floater->getStartConferenceInSameFloater()) { // Close the IM floater only if we are not planning to close the P2P chat // and start a new conference in the same floater. im_floater->closeFloater(); } getChicletPanel()->removeChiclet(session_id); } } void LLChicletBar::sessionIDUpdated(const LLUUID& old_session_id, const LLUUID& new_session_id) { //this is only needed in case of outgoing ad-hoc/group chat sessions LLChicletPanel* chiclet_panel = getChicletPanel(); if (chiclet_panel) { //it should be ad-hoc im chiclet or group im chiclet LLChiclet* chiclet = chiclet_panel->findChiclet<LLChiclet>(old_session_id); if (chiclet) chiclet->setSessionId(new_session_id); } } S32 LLChicletBar::getTotalUnreadIMCount() { return getChicletPanel()->getTotalUnreadIMCount(); } BOOL LLChicletBar::postBuild() { mToolbarStack = getChild<LLLayoutStack>("toolbar_stack"); mChicletPanel = getChild<LLChicletPanel>("chiclet_list"); showWellButton("im_well", !LLIMWellWindow::getInstance()->isWindowEmpty()); showWellButton("notification_well", !LLNotificationWellWindow::getInstance()->isWindowEmpty()); LLPanelTopInfoBar::instance().setResizeCallback(boost::bind(&LLChicletBar::fitWithTopInfoBar, this)); LLPanelTopInfoBar::instance().setVisibleCallback(boost::bind(&LLChicletBar::fitWithTopInfoBar, this)); return TRUE; } void LLChicletBar::showWellButton(const std::string& well_name, bool visible) { LLView * panel = findChild<LLView>(well_name + "_panel"); if (!panel) return; panel->setVisible(visible); } void LLChicletBar::log(LLView* panel, const std::string& descr) { if (NULL == panel) return; LLView* layout = panel->getParent(); LL_DEBUGS("Chiclet Bar Rects") << descr << ": " << "panel: " << panel->getName() << ", rect: " << panel->getRect() << " layout: " << layout->getName() << ", rect: " << layout->getRect() << LL_ENDL; } void LLChicletBar::reshape(S32 width, S32 height, BOOL called_from_parent) { static S32 debug_calling_number = 0; lldebugs << "**************************************** " << ++debug_calling_number << llendl; S32 current_width = getRect().getWidth(); S32 delta_width = width - current_width; lldebugs << "Reshaping: " << ", width: " << width << ", cur width: " << current_width << ", delta_width: " << delta_width << ", called_from_parent: " << called_from_parent << llendl; if (mChicletPanel) log(mChicletPanel, "before"); // Difference between chiclet bar width required to fit its children and the actual width. (see EXT-991) // Positive value means that chiclet bar is not wide enough. // Negative value means that there is free space. static S32 extra_shrink_width = 0; bool should_be_reshaped = true; if (mChicletPanel && mToolbarStack) { // Firstly, update layout stack to ensure we deal with correct panel sizes. { // Force the updating of layout to reset panels collapse factor. mToolbarStack->updateLayout(); } // chiclet bar is narrowed if (delta_width < 0) { if (extra_shrink_width > 0) // not enough space { extra_shrink_width += llabs(delta_width); should_be_reshaped = false; } else { extra_shrink_width = processWidthDecreased(delta_width); // increase new width to extra_shrink_width value to not reshape less than chiclet bar minimum width += extra_shrink_width; } } // chiclet bar is widened else { if (extra_shrink_width > delta_width) { // Still not enough space. // Only subtract the delta from the required delta and don't reshape. extra_shrink_width -= delta_width; should_be_reshaped = false; } else if (extra_shrink_width > 0) { // If we have some extra shrink width let's reduce delta_width & width delta_width -= extra_shrink_width; width -= extra_shrink_width; extra_shrink_width = 0; } } } if (should_be_reshaped) { lldebugs << "Reshape all children with width: " << width << llendl; LLPanel::reshape(width, height, called_from_parent); } if (mChicletPanel) log(mChicletPanel, "after"); } S32 LLChicletBar::processWidthDecreased(S32 delta_width) { bool still_should_be_processed = true; const S32 chiclet_panel_shrink_headroom = getChicletPanelShrinkHeadroom(); // Decreasing width of chiclet panel. if (chiclet_panel_shrink_headroom > 0) { // we have some space to decrease chiclet panel S32 shrink_by = llmin(-delta_width, chiclet_panel_shrink_headroom); lldebugs << "delta_width: " << delta_width << ", panel_delta_min: " << chiclet_panel_shrink_headroom << ", shrink_by: " << shrink_by << llendl; // is chiclet panel wide enough to process resizing? delta_width += chiclet_panel_shrink_headroom; still_should_be_processed = delta_width < 0; lldebugs << "Shrinking chiclet panel by " << shrink_by << " px" << llendl; mChicletPanel->getParent()->reshape(mChicletPanel->getParent()->getRect().getWidth() - shrink_by, mChicletPanel->getParent()->getRect().getHeight()); log(mChicletPanel, "after processing panel decreasing via chiclet panel"); lldebugs << "RS_CHICLET_PANEL" << ", delta_width: " << delta_width << llendl; } S32 extra_shrink_width = 0; if (still_should_be_processed) { extra_shrink_width = -delta_width; llwarns << "There is no enough width to reshape all children: " << extra_shrink_width << llendl; } return extra_shrink_width; } S32 LLChicletBar::getChicletPanelShrinkHeadroom() const { static const S32 min_width = mChicletPanel->getMinWidth(); const S32 cur_width = mChicletPanel->getParent()->getRect().getWidth(); S32 shrink_headroom = cur_width - min_width; llassert(shrink_headroom >= 0); // the panel cannot get narrower than the minimum return shrink_headroom; } void LLChicletBar::fitWithTopInfoBar() { LLPanelTopInfoBar& top_info_bar = LLPanelTopInfoBar::instance(); LLRect rect = getRect(); S32 width = rect.getWidth(); if (top_info_bar.getVisible()) { S32 delta = top_info_bar.calcScreenRect().mRight - calcScreenRect().mLeft; if (delta < 0 && rect.mLeft < llabs(delta)) delta = -rect.mLeft; rect.setLeftTopAndSize(rect.mLeft + delta, rect.mTop, rect.getWidth(), rect.getHeight()); width = rect.getWidth() - delta; } else { LLView* parent = getParent(); if (parent) { LLRect parent_rect = parent->getRect(); rect.setLeftTopAndSize(0, rect.mTop, rect.getWidth(), rect.getHeight()); width = parent_rect.getWidth(); } } setRect(rect); LLPanel::reshape(width, rect.getHeight(), false); } <|endoftext|>
<commit_before>#include <cap/resistor_capacitor.h> #ifdef WITH_DEAL_II #include <cap/supercapacitor.h> #endif namespace cap { EnergyStorageDeviceBuilder:: ~EnergyStorageDeviceBuilder() = default; void EnergyStorageDeviceBuilder:: register_energy_storage_device(std::string const & type, EnergyStorageDeviceBuilder * builder) { EnergyStorageDevice::_builders[type] = builder; } std::map<std::string,EnergyStorageDeviceBuilder*> EnergyStorageDevice:: _builders = std::map<std::string,EnergyStorageDeviceBuilder*>(); std::unique_ptr<EnergyStorageDevice> EnergyStorageDevice:: build(boost::mpi::communicator const & comm, boost::property_tree::ptree const & ptree) { auto const type = ptree.get<std::string>("type"); auto const it = _builders.find(type); if (it != _builders.end()) return (it->second)->build(comm, ptree); else throw std::runtime_error("invalid EnergyStorageDevice type `"+type+"`\n"); } EnergyStorageDevice:: EnergyStorageDevice(boost::mpi::communicator const & communicator) : _communicator(communicator) { } std::shared_ptr<EnergyStorageDevice> buildEnergyStorageDevice(boost::mpi::communicator const & comm, boost::property_tree::ptree const & ptree) { std::string const type = ptree.get<std::string>("type", "unknown_type"); if (type.compare("SeriesRC") == 0) return std::make_shared<cap::SeriesRC>(comm, ptree); else if (type.compare("ParallelRC") == 0) return std::make_shared<cap::ParallelRC>(comm, ptree); else if (type.compare("SuperCapacitor") == 0) { #ifdef WITH_DEAL_II int const dim = ptree.get<int>("dim"); if (dim == 2) return std::make_shared<cap::SuperCapacitor<2>>(comm, ptree); else if (dim ==3) return std::make_shared<cap::SuperCapacitor<3>>(comm, ptree); else throw std::runtime_error("dim="+std::to_string(dim)+" must be 2 or 3"); #else throw std::runtime_error("reconfigure with deal.II"); #endif } else throw std::runtime_error("invalid energy storage type ``"+type+"''\n"); } EnergyStorageDevice:: ~EnergyStorageDevice() = default; void EnergyStorageDevice:: evolve_one_time_step_changing_voltage(double const time_step, double const voltage) { // this is meant to be a linear change of the voltage over the time step (ramp) // TODO: if not implemented use the step version this->evolve_one_time_step_constant_voltage(time_step, voltage); } void EnergyStorageDevice:: evolve_one_time_step_changing_current(double const time_step, double const current) { this->evolve_one_time_step_constant_current(time_step, current); } void EnergyStorageDevice:: evolve_one_time_step_changing_power(double const time_step, double const power) { this->evolve_one_time_step_constant_power(time_step, power); } void EnergyStorageDevice:: evolve_one_time_step_changing_load(double const time_step, double const load) { this->evolve_one_time_step_constant_load(time_step, load); } } // end namespace cap <commit_msg>add forgotten implementation for the destructor of the inspector base class<commit_after>#include <cap/resistor_capacitor.h> #ifdef WITH_DEAL_II #include <cap/supercapacitor.h> #endif namespace cap { EnergyStorageDeviceInspector:: ~EnergyStorageDeviceInspector() = default; EnergyStorageDeviceBuilder:: ~EnergyStorageDeviceBuilder() = default; void EnergyStorageDeviceBuilder:: register_energy_storage_device(std::string const & type, EnergyStorageDeviceBuilder * builder) { EnergyStorageDevice::_builders[type] = builder; } std::map<std::string,EnergyStorageDeviceBuilder*> EnergyStorageDevice:: _builders = std::map<std::string,EnergyStorageDeviceBuilder*>(); std::unique_ptr<EnergyStorageDevice> EnergyStorageDevice:: build(boost::mpi::communicator const & comm, boost::property_tree::ptree const & ptree) { auto const type = ptree.get<std::string>("type"); auto const it = _builders.find(type); if (it != _builders.end()) return (it->second)->build(comm, ptree); else throw std::runtime_error("invalid EnergyStorageDevice type `"+type+"`\n"); } EnergyStorageDevice:: EnergyStorageDevice(boost::mpi::communicator const & communicator) : _communicator(communicator) { } std::shared_ptr<EnergyStorageDevice> buildEnergyStorageDevice(boost::mpi::communicator const & comm, boost::property_tree::ptree const & ptree) { std::string const type = ptree.get<std::string>("type", "unknown_type"); if (type.compare("SeriesRC") == 0) return std::make_shared<cap::SeriesRC>(comm, ptree); else if (type.compare("ParallelRC") == 0) return std::make_shared<cap::ParallelRC>(comm, ptree); else if (type.compare("SuperCapacitor") == 0) { #ifdef WITH_DEAL_II int const dim = ptree.get<int>("dim"); if (dim == 2) return std::make_shared<cap::SuperCapacitor<2>>(comm, ptree); else if (dim ==3) return std::make_shared<cap::SuperCapacitor<3>>(comm, ptree); else throw std::runtime_error("dim="+std::to_string(dim)+" must be 2 or 3"); #else throw std::runtime_error("reconfigure with deal.II"); #endif } else throw std::runtime_error("invalid energy storage type ``"+type+"''\n"); } EnergyStorageDevice:: ~EnergyStorageDevice() = default; void EnergyStorageDevice:: evolve_one_time_step_changing_voltage(double const time_step, double const voltage) { // this is meant to be a linear change of the voltage over the time step (ramp) // TODO: if not implemented use the step version this->evolve_one_time_step_constant_voltage(time_step, voltage); } void EnergyStorageDevice:: evolve_one_time_step_changing_current(double const time_step, double const current) { this->evolve_one_time_step_constant_current(time_step, current); } void EnergyStorageDevice:: evolve_one_time_step_changing_power(double const time_step, double const power) { this->evolve_one_time_step_constant_power(time_step, power); } void EnergyStorageDevice:: evolve_one_time_step_changing_load(double const time_step, double const load) { this->evolve_one_time_step_constant_load(time_step, load); } } // end namespace cap <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fmteiro.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-01-05 15:49:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FMTEIRO_HXX #define _FMTEIRO_HXX #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _FORMAT_HXX //autogen #include <format.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class IntlWrapper; class SW_DLLPUBLIC SwFmtEditInReadonly : public SfxBoolItem { public: SwFmtEditInReadonly( USHORT nId = RES_EDIT_IN_READONLY, BOOL bPrt = FALSE ) : SfxBoolItem( nId, bPrt ) {} // "pure virtual Methoden" vom SfxPoolItem virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper* pIntl = 0 ) const; }; inline const SwFmtEditInReadonly &SwAttrSet::GetEditInReadonly(BOOL bInP) const { return (const SwFmtEditInReadonly&)Get( RES_EDIT_IN_READONLY,bInP); } inline const SwFmtEditInReadonly &SwFmt::GetEditInReadonly(BOOL bInP) const { return aSet.GetEditInReadonly(bInP); } #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.7.406); FILE MERGED 2005/09/05 13:36:02 rt 1.7.406.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmteiro.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:48:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FMTEIRO_HXX #define _FMTEIRO_HXX #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _FORMAT_HXX //autogen #include <format.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class IntlWrapper; class SW_DLLPUBLIC SwFmtEditInReadonly : public SfxBoolItem { public: SwFmtEditInReadonly( USHORT nId = RES_EDIT_IN_READONLY, BOOL bPrt = FALSE ) : SfxBoolItem( nId, bPrt ) {} // "pure virtual Methoden" vom SfxPoolItem virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres, SfxMapUnit eCoreMetric, SfxMapUnit ePresMetric, String &rText, const IntlWrapper* pIntl = 0 ) const; }; inline const SwFmtEditInReadonly &SwAttrSet::GetEditInReadonly(BOOL bInP) const { return (const SwFmtEditInReadonly&)Get( RES_EDIT_IN_READONLY,bInP); } inline const SwFmtEditInReadonly &SwFmt::GetEditInReadonly(BOOL bInP) const { return aSet.GetEditInReadonly(bInP); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: redline.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:06:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _REDLINE_HXX #define _REDLINE_HXX #ifndef _DATETIME_HXX //autogen #include <tools/datetime.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _REDLENUM_HXX #include <redlenum.hxx> #endif class SfxItemSet; class SwRedlineExtraData { SwRedlineExtraData( const SwRedlineExtraData& ); SwRedlineExtraData& operator=( const SwRedlineExtraData& ); protected: SwRedlineExtraData() {} public: virtual ~SwRedlineExtraData(); virtual SwRedlineExtraData* CreateNew() const = 0; virtual void Accept( SwPaM& rPam ) const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; }; class SwRedlineExtraData_FmtColl : public SwRedlineExtraData { String sFmtNm; SfxItemSet* pSet; USHORT nPoolId; public: SwRedlineExtraData_FmtColl( const String& rColl, USHORT nPoolFmtId, const SfxItemSet* pSet = 0 ); virtual ~SwRedlineExtraData_FmtColl(); virtual SwRedlineExtraData* CreateNew() const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; void SetItemSet( const SfxItemSet& rSet ); }; class SwRedlineExtraData_Format : public SwRedlineExtraData { SvUShorts aWhichIds; SwRedlineExtraData_Format( const SwRedlineExtraData_Format& rCpy ); public: SwRedlineExtraData_Format( const SfxItemSet& rSet ); virtual ~SwRedlineExtraData_Format(); virtual SwRedlineExtraData* CreateNew() const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; }; class SwRedlineData { friend class SwRedline; SwRedlineData* pNext; // Verweis auf weitere Daten SwRedlineExtraData* pExtraData; String sComment; DateTime aStamp; SwRedlineType eType; USHORT nAuthor, nSeqNo; public: SwRedlineData( SwRedlineType eT, USHORT nAut ); SwRedlineData( const SwRedlineData& rCpy, BOOL bCpyNext = TRUE ); // fuer sw3io: pNext/pExtraData gehen in eigenen Besitz ueber! SwRedlineData( SwRedlineType eT, USHORT nAut, const DateTime& rDT, const String& rCmnt, SwRedlineData* pNxt, SwRedlineExtraData* pExtraData = 0 ); ~SwRedlineData(); int operator==( const SwRedlineData& rCmp ) const { return nAuthor == rCmp.nAuthor && eType == rCmp.eType && sComment == rCmp.sComment && (( !pNext && !rCmp.pNext ) || ( pNext && rCmp.pNext && *pNext == *rCmp.pNext )) && (( !pExtraData && !rCmp.pExtraData ) || ( pExtraData && rCmp.pExtraData && *pExtraData == *rCmp.pExtraData )); } int operator!=( const SwRedlineData& rCmp ) const { return !operator==( rCmp ); } SwRedlineType GetType() const { return SwRedlineType( eType & REDLINE_NO_FLAG_MASK); } SwRedlineType GetRealType() const { return eType; } USHORT GetAuthor() const { return nAuthor; } const String& GetComment() const { return sComment; } const DateTime& GetTimeStamp() const { return aStamp; } inline const SwRedlineData* Next() const{ return pNext; } void SetTimeStamp( const DateTime& rDT) { aStamp = rDT; aStamp.SetSec( 0 ); aStamp.Set100Sec( 0 ); } void SetComment( const String& rS ) { sComment = rS; } void SetAutoFmtFlag() { eType = SwRedlineType( eType | REDLINE_FORM_AUTOFMT ); } int CanCombine( const SwRedlineData& rCmp ) const { return nAuthor == rCmp.nAuthor && eType == rCmp.eType && sComment == rCmp.sComment && GetTimeStamp() == rCmp.GetTimeStamp() && (( !pNext && !rCmp.pNext ) || ( pNext && rCmp.pNext && pNext->CanCombine( *rCmp.pNext ))) && (( !pExtraData && !rCmp.pExtraData ) || ( pExtraData && rCmp.pExtraData && *pExtraData == *rCmp.pExtraData )); } // ExtraData wird kopiert, der Pointer geht also NICHT in den Besitz // des RedlineObjectes! void SetExtraData( const SwRedlineExtraData* pData ); const SwRedlineExtraData* GetExtraData() const { return pExtraData; } // fuers UI-seitige zusammenfassen von Redline-Actionen. Wird z.Z. nur // fuers Autoformat mit Redline benoetigt. Der Wert != 0 bedeutet dabei, // das es noch weitere geben kann! USHORT GetSeqNo() const { return nSeqNo; } void SetSeqNo( USHORT nNo ) { nSeqNo = nNo; } String GetDescr() const; }; class SwRedline : public SwPaM { SwRedlineData* pRedlineData; SwNodeIndex* pCntntSect; BOOL bDelLastPara : 1; BOOL bIsLastParaDelete : 1; BOOL bIsVisible : 1; void MoveToSection(); void CopyToSection(); void DelCopyOfSection(); void MoveFromSection(); public: SwRedline( SwRedlineType eType, const SwPaM& rPam ); SwRedline( const SwRedlineData& rData, const SwPaM& rPam ); SwRedline( const SwRedlineData& rData, const SwPosition& rPos ); // fuer sw3io: pData geht in eigenen Besitz ueber! SwRedline(SwRedlineData* pData, const SwPosition& rPos, BOOL bVsbl, BOOL bDelLP, BOOL bIsPD) : SwPaM( rPos ), pRedlineData( pData ), pCntntSect( 0 ), bDelLastPara( bDelLP ), bIsLastParaDelete( bIsPD ), bIsVisible( bVsbl ) {} SwRedline( const SwRedline& ); virtual ~SwRedline(); SwNodeIndex* GetContentIdx() const { return pCntntSect; } // fuers Undo void SetContentIdx( const SwNodeIndex* ); BOOL IsVisible() const { return bIsVisible; } BOOL IsDelLastPara() const { return bDelLastPara; } BOOL IsLastParaDelete() const { return bIsLastParaDelete; } // das BOOL besagt, ob nach dem setzen der Pos kein Bereich mehr // aufgespannt ist. -> TRUE, ansonten Bereich und FALSE void SetStart( const SwPosition& rPos, SwPosition* pSttPtr = 0 ) { if( !pSttPtr ) pSttPtr = Start(); *pSttPtr = rPos; } void SetEnd( const SwPosition& rPos, SwPosition* pEndPtr = 0 ) { if( !pEndPtr ) pEndPtr = End(); *pEndPtr = rPos; } // liegt eine gueltige Selektion vor? BOOL HasValidRange() const; const SwRedlineData& GetRedlineData(USHORT nPos = 0) const; int operator==( const SwRedlineData& rCmp ) const { return *pRedlineData == rCmp; } int operator!=( const SwRedlineData& rCmp ) const { return *pRedlineData != rCmp; } void SetAutoFmtFlag() { pRedlineData->SetAutoFmtFlag(); } USHORT GetStackCount() const; USHORT GetAuthor( USHORT nPos = 0) const; const String& GetAuthorString( USHORT nPos = 0 ) const; const DateTime& GetTimeStamp( USHORT nPos = 0) const; SwRedlineType GetRealType( USHORT nPos = 0 ) const; SwRedlineType GetType( USHORT nPos = 0) const { return SwRedlineType( GetRealType( nPos ) & REDLINE_NO_FLAG_MASK); } const String& GetComment( USHORT nPos = 0 ) const; void SetComment( const String& rS ) { pRedlineData->SetComment( rS ); } // ExtraData wird kopiert, der Pointer geht also NICHT in den Besitz // des RedlineObjectes! void SetExtraData( const SwRedlineExtraData* pData ) { pRedlineData->SetExtraData( pData ); } const SwRedlineExtraData* GetExtraData() const { return pRedlineData->GetExtraData(); } // fuers UI-seitige zusammenfassen von Redline-Actionen. Wird z.Z. nur // fuers Autoformat mit Redline benoetigt. Der Wert != 0 bedeutet dabei, // das es noch weitere geben kann! USHORT GetSeqNo() const { return pRedlineData->GetSeqNo(); } void SetSeqNo( USHORT nNo ) { pRedlineData->SetSeqNo( nNo ); } // Beim Hide/ShowOriginal wird 2 mal ueber die Liste gelaufen, damit // die Del-Redlines per Copy und Delete versteckt werden. Beim Move // wird sonst die Attributierung falsch behandelt. // Alle anderen Aufrufer muessen immer 0 angeben. void CallDisplayFunc( USHORT nLoop = 0 ); void Show( USHORT nLoop = 0 ); void Hide( USHORT nLoop = 0 ); void ShowOriginal( USHORT nLoop = 0 ); // calculates the intersection with text node number nNdIdx void CalcStartEnd( ULONG nNdIdx, USHORT& nStart, USHORT& nEnd ) const; void InvalidateRange(); // das Layout anstossen BOOL IsOwnRedline( const SwRedline& rRedl ) const { return GetAuthor() == rRedl.GetAuthor(); } BOOL CanCombine( const SwRedline& rRedl ) const; void PushData( const SwRedline& rRedl, BOOL bOwnAsNext = TRUE ); BOOL PopData(); // #111827# /** Returns textual description of this a redline data element of this redline. @param nPos index of the redline data element to describe The textual description of the selected element contains the kind of redline and the possibly shortened text of the redline. @return textual description of the selected redline data element */ String GetDescr(USHORT nPos = 0); int operator==( const SwRedline& ) const; int operator<( const SwRedline& ) const; }; #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.8.48); FILE MERGED 2005/09/13 11:50:09 tra 1.8.48.3: RESYNC: (1.8-1.9); FILE MERGED 2005/08/31 12:50:43 tra 1.8.48.2: #i50348# Introducing IDocumentRedlineAccess interface 2005/06/07 14:10:13 fme 1.8.48.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: redline.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:30:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _REDLINE_HXX #define _REDLINE_HXX #ifndef _DATETIME_HXX //autogen #include <tools/datetime.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #define _SVSTDARR_USHORTS #include <svtools/svstdarr.hxx> #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef IDOCUMENTREDLINEACCESS_HXX_INCLUDED #include <IDocumentRedlineAccess.hxx> #endif class SfxItemSet; class SwRedlineExtraData { SwRedlineExtraData( const SwRedlineExtraData& ); SwRedlineExtraData& operator=( const SwRedlineExtraData& ); protected: SwRedlineExtraData() {} public: virtual ~SwRedlineExtraData(); virtual SwRedlineExtraData* CreateNew() const = 0; virtual void Accept( SwPaM& rPam ) const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; }; class SwRedlineExtraData_FmtColl : public SwRedlineExtraData { String sFmtNm; SfxItemSet* pSet; USHORT nPoolId; public: SwRedlineExtraData_FmtColl( const String& rColl, USHORT nPoolFmtId, const SfxItemSet* pSet = 0 ); virtual ~SwRedlineExtraData_FmtColl(); virtual SwRedlineExtraData* CreateNew() const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; void SetItemSet( const SfxItemSet& rSet ); }; class SwRedlineExtraData_Format : public SwRedlineExtraData { SvUShorts aWhichIds; SwRedlineExtraData_Format( const SwRedlineExtraData_Format& rCpy ); public: SwRedlineExtraData_Format( const SfxItemSet& rSet ); virtual ~SwRedlineExtraData_Format(); virtual SwRedlineExtraData* CreateNew() const; virtual void Reject( SwPaM& rPam ) const; virtual int operator == ( const SwRedlineExtraData& ) const; }; class SwRedlineData { friend class SwRedline; SwRedlineData* pNext; // Verweis auf weitere Daten SwRedlineExtraData* pExtraData; String sComment; DateTime aStamp; IDocumentRedlineAccess::RedlineType_t eType; USHORT nAuthor, nSeqNo; public: SwRedlineData( IDocumentRedlineAccess::RedlineType_t eT, USHORT nAut ); SwRedlineData( const SwRedlineData& rCpy, BOOL bCpyNext = TRUE ); // fuer sw3io: pNext/pExtraData gehen in eigenen Besitz ueber! SwRedlineData( IDocumentRedlineAccess::RedlineType_t eT, USHORT nAut, const DateTime& rDT, const String& rCmnt, SwRedlineData* pNxt, SwRedlineExtraData* pExtraData = 0 ); ~SwRedlineData(); int operator==( const SwRedlineData& rCmp ) const { return nAuthor == rCmp.nAuthor && eType == rCmp.eType && sComment == rCmp.sComment && (( !pNext && !rCmp.pNext ) || ( pNext && rCmp.pNext && *pNext == *rCmp.pNext )) && (( !pExtraData && !rCmp.pExtraData ) || ( pExtraData && rCmp.pExtraData && *pExtraData == *rCmp.pExtraData )); } int operator!=( const SwRedlineData& rCmp ) const { return !operator==( rCmp ); } IDocumentRedlineAccess::RedlineType_t GetType() const { return (eType & IDocumentRedlineAccess::REDLINE_NO_FLAG_MASK); } IDocumentRedlineAccess::RedlineType_t GetRealType() const { return eType; } USHORT GetAuthor() const { return nAuthor; } const String& GetComment() const { return sComment; } const DateTime& GetTimeStamp() const { return aStamp; } inline const SwRedlineData* Next() const{ return pNext; } void SetComment( const String& rS ) { sComment = rS; } void SetAutoFmtFlag() { eType = ( eType | IDocumentRedlineAccess::REDLINE_FORM_AUTOFMT ); } int CanCombine( const SwRedlineData& rCmp ) const { return nAuthor == rCmp.nAuthor && eType == rCmp.eType && sComment == rCmp.sComment && GetTimeStamp() == rCmp.GetTimeStamp() && (( !pNext && !rCmp.pNext ) || ( pNext && rCmp.pNext && pNext->CanCombine( *rCmp.pNext ))) && (( !pExtraData && !rCmp.pExtraData ) || ( pExtraData && rCmp.pExtraData && *pExtraData == *rCmp.pExtraData )); } // ExtraData wird kopiert, der Pointer geht also NICHT in den Besitz // des RedlineObjectes! void SetExtraData( const SwRedlineExtraData* pData ); const SwRedlineExtraData* GetExtraData() const { return pExtraData; } // fuers UI-seitige zusammenfassen von Redline-Actionen. Wird z.Z. nur // fuers Autoformat mit Redline benoetigt. Der Wert != 0 bedeutet dabei, // das es noch weitere geben kann! USHORT GetSeqNo() const { return nSeqNo; } void SetSeqNo( USHORT nNo ) { nSeqNo = nNo; } String GetDescr() const; }; class SwRedline : public SwPaM { SwRedlineData* pRedlineData; SwNodeIndex* pCntntSect; BOOL bDelLastPara : 1; BOOL bIsLastParaDelete : 1; BOOL bIsVisible : 1; void MoveToSection(); void CopyToSection(); void DelCopyOfSection(); void MoveFromSection(); public: SwRedline( IDocumentRedlineAccess::RedlineType_t eType, const SwPaM& rPam ); SwRedline( const SwRedlineData& rData, const SwPaM& rPam ); SwRedline( const SwRedlineData& rData, const SwPosition& rPos ); // fuer sw3io: pData geht in eigenen Besitz ueber! SwRedline(SwRedlineData* pData, const SwPosition& rPos, BOOL bVsbl, BOOL bDelLP, BOOL bIsPD) : SwPaM( rPos ), pRedlineData( pData ), pCntntSect( 0 ), bDelLastPara( bDelLP ), bIsLastParaDelete( bIsPD ), bIsVisible( bVsbl ) {} SwRedline( const SwRedline& ); virtual ~SwRedline(); SwNodeIndex* GetContentIdx() const { return pCntntSect; } // fuers Undo void SetContentIdx( const SwNodeIndex* ); BOOL IsVisible() const { return bIsVisible; } BOOL IsDelLastPara() const { return bDelLastPara; } // das BOOL besagt, ob nach dem setzen der Pos kein Bereich mehr // aufgespannt ist. -> TRUE, ansonten Bereich und FALSE void SetStart( const SwPosition& rPos, SwPosition* pSttPtr = 0 ) { if( !pSttPtr ) pSttPtr = Start(); *pSttPtr = rPos; } void SetEnd( const SwPosition& rPos, SwPosition* pEndPtr = 0 ) { if( !pEndPtr ) pEndPtr = End(); *pEndPtr = rPos; } // liegt eine gueltige Selektion vor? BOOL HasValidRange() const; const SwRedlineData& GetRedlineData(USHORT nPos = 0) const; int operator==( const SwRedlineData& rCmp ) const { return *pRedlineData == rCmp; } int operator!=( const SwRedlineData& rCmp ) const { return *pRedlineData != rCmp; } void SetAutoFmtFlag() { pRedlineData->SetAutoFmtFlag(); } USHORT GetStackCount() const; USHORT GetAuthor( USHORT nPos = 0) const; const String& GetAuthorString( USHORT nPos = 0 ) const; const DateTime& GetTimeStamp( USHORT nPos = 0) const; IDocumentRedlineAccess::RedlineType_t GetRealType( USHORT nPos = 0 ) const; IDocumentRedlineAccess::RedlineType_t GetType( USHORT nPos = 0) const { return ( GetRealType( nPos ) & IDocumentRedlineAccess::REDLINE_NO_FLAG_MASK); } const String& GetComment( USHORT nPos = 0 ) const; void SetComment( const String& rS ) { pRedlineData->SetComment( rS ); } // ExtraData wird kopiert, der Pointer geht also NICHT in den Besitz // des RedlineObjectes! void SetExtraData( const SwRedlineExtraData* pData ) { pRedlineData->SetExtraData( pData ); } const SwRedlineExtraData* GetExtraData() const { return pRedlineData->GetExtraData(); } // fuers UI-seitige zusammenfassen von Redline-Actionen. Wird z.Z. nur // fuers Autoformat mit Redline benoetigt. Der Wert != 0 bedeutet dabei, // das es noch weitere geben kann! USHORT GetSeqNo() const { return pRedlineData->GetSeqNo(); } void SetSeqNo( USHORT nNo ) { pRedlineData->SetSeqNo( nNo ); } // Beim Hide/ShowOriginal wird 2 mal ueber die Liste gelaufen, damit // die Del-Redlines per Copy und Delete versteckt werden. Beim Move // wird sonst die Attributierung falsch behandelt. // Alle anderen Aufrufer muessen immer 0 angeben. void CallDisplayFunc( USHORT nLoop = 0 ); void Show( USHORT nLoop = 0 ); void Hide( USHORT nLoop = 0 ); void ShowOriginal( USHORT nLoop = 0 ); // calculates the intersection with text node number nNdIdx void CalcStartEnd( ULONG nNdIdx, USHORT& nStart, USHORT& nEnd ) const; void InvalidateRange(); // das Layout anstossen BOOL IsOwnRedline( const SwRedline& rRedl ) const { return GetAuthor() == rRedl.GetAuthor(); } BOOL CanCombine( const SwRedline& rRedl ) const; void PushData( const SwRedline& rRedl, BOOL bOwnAsNext = TRUE ); BOOL PopData(); // #111827# /** Returns textual description of this a redline data element of this redline. @param nPos index of the redline data element to describe The textual description of the selected element contains the kind of redline and the possibly shortened text of the redline. @return textual description of the selected redline data element */ String GetDescr(USHORT nPos = 0); int operator==( const SwRedline& ) const; int operator<( const SwRedline& ) const; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: splargs.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-10-05 13:19:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SPLARGS_HXX #define _SPLARGS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #include <limits.h> // USHRT_MAX #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif class SwTxtNode; class SwIndex; class SpellCheck; #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_ #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLCHECKER1_HPP_ #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_ #include <com/sun/star/linguistic2/XHyphenatedWord.hpp> #endif /************************************************************************* * struct SwArgsBase *************************************************************************/ struct SwArgsBase // used for text conversion (Hangul/Hanja, ...) { SwTxtNode *pStartNode; SwIndex *pStartIdx; SwTxtNode *pEndNode; SwIndex *pEndIdx; SwArgsBase( SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : pStartNode( pStart ), pStartIdx( &rStart ), pEndNode( pEnd ), pEndIdx( &rEnd ) {} void SetStart(SwTxtNode* pStart, SwIndex& rStart ) { pStartNode = pStart; pStartIdx = &rStart ; } void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd ) { pEndNode = pEnd; pEndIdx = &rEnd ; } }; /************************************************************************* * struct SwConversionArgs * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...) *************************************************************************/ struct SwConversionArgs : SwArgsBase { rtl::OUString aConvText; // convertible text found LanguageType nConvSrcLang; // (source) language to look for LanguageType nConvTextLang; // language of aConvText (if the latter one was found) // used for chinese translation LanguageType nConvTargetLang; // target language of text to be changed const Font *pTargetFont; // target font of text to be changed // explicitly enables or disables application of the above two sal_Bool bAllowImplicitChangesForNotConvertibleText; SwConversionArgs( LanguageType nLang, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), nConvSrcLang( nLang ), nConvTextLang( LANGUAGE_NONE ), nConvTargetLang( LANGUAGE_NONE ), pTargetFont( NULL ), bAllowImplicitChangesForNotConvertibleText( sal_False ) {} }; /************************************************************************* * struct SwSpellArgs *************************************************************************/ struct SwSpellArgs : SwArgsBase { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpeller; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt; SwSpellArgs(::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), xSpeller( rxSplChk ) {} }; /************************************************************************* * class SwInterHyphInfo *************************************************************************/ // Parameter-Klasse fuer Hyphenate // docedt.cxx: SwDoc::Hyphenate() // txtedt.cxx: SwTxtNode::Hyphenate() // txthyph.cxx: SwTxtFrm::Hyphenate() class SwInterHyphInfo { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > xHyphWord; const Point aCrsrPos; sal_Bool bAuto : 1; sal_Bool bNoLang : 1; sal_Bool bCheck : 1; public: xub_StrLen nStart; xub_StrLen nLen; xub_StrLen nWordStart; xub_StrLen nWordLen; xub_StrLen nHyphPos; sal_uInt16 nMinTrail; inline SwInterHyphInfo( const Point &rCrsrPos, const sal_uInt16 nStart = 0, const sal_uInt16 nLen = USHRT_MAX ) : aCrsrPos( rCrsrPos ), bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False), nStart(nStart), nLen(nLen), nWordStart(0), nWordLen(0), nHyphPos(0), nMinTrail(0) { } inline xub_StrLen GetStart() const { return nStart; } inline xub_StrLen GetLen() const { return nLen; } inline xub_StrLen GetEnd() const { return STRING_LEN == nLen ? nLen : nStart + nLen; } inline const Point *GetCrsrPos() const { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; } inline sal_Bool IsAuto() const { return bAuto; } inline void SetAuto( const sal_Bool bNew ) { bAuto = bNew; } inline sal_Bool IsCheck() const { return bCheck; } inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; } inline sal_Bool IsNoLang() const { return bNoLang; } inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; } inline void SetHyphWord(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > &rxHW) { xHyphWord = rxHW; } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > GetHyphWord() { return xHyphWord; } }; #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.2.78); FILE MERGED 2005/10/25 08:22:30 tra 1.2.78.3: RESYNC: (1.3-1.4); FILE MERGED 2005/09/13 11:54:21 tra 1.2.78.2: RESYNC: (1.2-1.3); FILE MERGED 2005/06/07 14:10:16 fme 1.2.78.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: splargs.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:31:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SPLARGS_HXX #define _SPLARGS_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #include <limits.h> // USHRT_MAX #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif class SwTxtNode; class SwIndex; class SpellCheck; #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_ #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLCHECKER1_HPP_ #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #endif #ifndef _COM_SUN_STAR_LINGUISTIC2_XHYPHENATEDWORD_HPP_ #include <com/sun/star/linguistic2/XHyphenatedWord.hpp> #endif /************************************************************************* * struct SwArgsBase *************************************************************************/ struct SwArgsBase // used for text conversion (Hangul/Hanja, ...) { SwTxtNode *pStartNode; SwIndex *pStartIdx; SwTxtNode *pEndNode; SwIndex *pEndIdx; SwArgsBase( SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : pStartNode( pStart ), pStartIdx( &rStart ), pEndNode( pEnd ), pEndIdx( &rEnd ) {} void SetStart(SwTxtNode* pStart, SwIndex& rStart ) { pStartNode = pStart; pStartIdx = &rStart ; } void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd ) { pEndNode = pEnd; pEndIdx = &rEnd ; } }; /************************************************************************* * struct SwConversionArgs * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...) *************************************************************************/ struct SwConversionArgs : SwArgsBase { rtl::OUString aConvText; // convertible text found LanguageType nConvSrcLang; // (source) language to look for LanguageType nConvTextLang; // language of aConvText (if the latter one was found) // used for chinese translation LanguageType nConvTargetLang; // target language of text to be changed const Font *pTargetFont; // target font of text to be changed // explicitly enables or disables application of the above two sal_Bool bAllowImplicitChangesForNotConvertibleText; SwConversionArgs( LanguageType nLang, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), nConvSrcLang( nLang ), nConvTextLang( LANGUAGE_NONE ), nConvTargetLang( LANGUAGE_NONE ), pTargetFont( NULL ), bAllowImplicitChangesForNotConvertibleText( sal_False ) {} }; /************************************************************************* * struct SwSpellArgs *************************************************************************/ struct SwSpellArgs : SwArgsBase { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpeller; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt; SwSpellArgs(::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), xSpeller( rxSplChk ) {} }; /************************************************************************* * class SwInterHyphInfo *************************************************************************/ // Parameter-Klasse fuer Hyphenate // docedt.cxx: SwDoc::Hyphenate() // txtedt.cxx: SwTxtNode::Hyphenate() // txthyph.cxx: SwTxtFrm::Hyphenate() class SwInterHyphInfo { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > xHyphWord; const Point aCrsrPos; sal_Bool bAuto : 1; sal_Bool bNoLang : 1; sal_Bool bCheck : 1; public: xub_StrLen nStart; xub_StrLen nLen; xub_StrLen nWordStart; xub_StrLen nWordLen; xub_StrLen nHyphPos; sal_uInt16 nMinTrail; inline SwInterHyphInfo( const Point &rCrsrPos, const sal_uInt16 nStart = 0, const sal_uInt16 nLen = USHRT_MAX ) : aCrsrPos( rCrsrPos ), bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False), nStart(nStart), nLen(nLen), nWordStart(0), nWordLen(0), nHyphPos(0), nMinTrail(0) { } inline xub_StrLen GetEnd() const { return STRING_LEN == nLen ? nLen : nStart + nLen; } inline const Point *GetCrsrPos() const { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; } inline sal_Bool IsCheck() const { return bCheck; } inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; } inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; } inline void SetHyphWord(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > &rxHW) { xHyphWord = rxHW; } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > GetHyphWord() { return xHyphWord; } }; #endif <|endoftext|>
<commit_before>#ifdef _DEBUG #include "testdatapath.h" #endif #include <opencv2/opencv.hpp> #include <iostream> #include <string> using namespace std; //画像表示用関数 int showImage(const cv::Mat& image, int wait = 0){ static const string wname("EBookChecker"); cv::imshow(wname, image); return cv::waitKey(wait); } class Range{ public: int start; int end; Range(int start, int end) :start(start), end(end){} Range():start(-1), end(-1){} }; //横方向をしらべる //文字のない範囲をvectorで返す void findSameValueHorizontal(const cv::Mat& src, std::vector<Range>& ranges) { //積分画像が欲しい CV_Assert(src.type() == CV_32SC1); //値が入っているかもしれないので空にする ranges.clear(); //積分画像はintなのでint型のポインタを取得。下端なので位置はsrc.rows - 1 const int* srcLine = src.ptr<int>(src.rows - 1); Range range; for (int i = 1; i < src.cols; i++){ //左隣と同じ値 bool sameValue = srcLine[i] == srcLine[i - 1]; //左隣と同じ値 かつ 範囲のstartが初期値(-1)のとき if (sameValue && range.start < 0){ //文字のない範囲の始まり range.start = i - 1; } //左隣と違う値 かつ 範囲のstartが代入済み else if (!sameValue && range.start >= 0){ //文字のない範囲の終わり range.end = i - 1; //結果として保存 ranges.push_back(range); //文字のない範囲を初期値に戻す range.start = -1; range.end = -1; } } //最後の範囲が画像の右端まである場合はfor文を抜けてから結果を保存する //文字のない範囲のstartは代入済み かつ 範囲のendは初期値のとき if (range.start >= 0 && range.end < 0){ range.end = src.cols - 1; ranges.push_back(range); } } int main(int argc, char** argv) { #ifndef _DEBUG //コマンドライン引数の解析。デバッグの時は使わない string commandArgs = "@input | | processing one image or image named serial number" ; cv::CommandLineParser parser(argc, argv, commandArgs); string src = parser.get<string>(0); #else string src = TEST_DATA_0; #endif cout << "input file:" << src << endl; //画像の読み込み。グレースケール画像として読み込む cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE); CV_Assert(image.channels() == 1 && image.type() == CV_8UC1); showImage(image); //二値化 cv::Mat binary; int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。 int binaryThreshold = 128; cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV); CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1); showImage(binary); cv::imwrite("binary.jpg", binary); //積分画像の生成 cv::Mat integral; cv::integral(binary, integral); CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1); showImage(integral); cv::imwrite("integral.jpg", integral); //積分画像を見やすくする処理 cv::Mat integralVisible; double max; double min; cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う CV_Assert(min == 0.0);//本当に最小値が0になっているか確認 integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。 showImage(integralVisible); cv::imwrite("integralVisible.jpg", integralVisible); //文字のない範囲を受け取る変数 vector<Range> horizontalRanges; findSameValueHorizontal(integral, horizontalRanges); //文字のない範囲を書き込む画像 cv::Mat horizontalRangeDst; //1チャンネルの原画像から3チャンネルの画像を作る cv::Mat srcArray[] = {image, image, image}; cv::merge(srcArray, 3, horizontalRangeDst); //文字のない範囲を3チャンネルの原画像に書き込む for (size_t i = 0; i < horizontalRanges.size(); i++){ Range& r = horizontalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(r.start, 0, r.end - r.start + 1, horizontalRangeDst.rows); cv::Mat roi(horizontalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(240, 176, 0); } showImage(horizontalRangeDst); cv::imwrite("horizontalDst.jpg", horizontalRangeDst); }<commit_msg>縦方向をしらべるプログラムの追加 縦方向と横方法の結果を合わせて表示するプログラムを追加<commit_after>#ifdef _DEBUG #include "testdatapath.h" #endif #include <opencv2/opencv.hpp> #include <iostream> #include <string> using namespace std; //画像表示用関数 int showImage(const cv::Mat& image, int wait = 0){ static const string wname("EBookChecker"); cv::imshow(wname, image); return cv::waitKey(wait); } class Range{ public: int start; int end; Range(int start, int end) :start(start), end(end){} Range():start(-1), end(-1){} }; //横方向をしらべる //文字のない範囲をvectorで返す void findSameValueHorizontal(const cv::Mat& src, std::vector<Range>& ranges) { //積分画像が欲しい CV_Assert(src.type() == CV_32SC1); //値が入っているかもしれないので空にする ranges.clear(); //積分画像はintなのでint型のポインタを取得。下端なので位置はsrc.rows - 1 const int* srcLine = src.ptr<int>(src.rows - 1); Range range; for (int i = 1; i < src.cols; i++){ //左隣と同じ値 bool sameValue = srcLine[i] == srcLine[i - 1]; //左隣と同じ値 かつ 範囲のstartが初期値(-1)のとき if (sameValue && range.start < 0){ //文字のない範囲の始まり range.start = i - 1; } //左隣と違う値 かつ 範囲のstartが代入済み else if (!sameValue && range.start >= 0){ //文字のない範囲の終わり range.end = i - 1; //結果として保存 ranges.push_back(range); //文字のない範囲を初期値に戻す range.start = -1; range.end = -1; } } //最後の範囲が画像の右端まである場合はfor文を抜けてから結果を保存する //文字のない範囲のstartは代入済み かつ 範囲のendは初期値のとき if (range.start >= 0 && range.end < 0){ range.end = src.cols - 1; ranges.push_back(range); } } //縦方向をしらべる //文字のない範囲をvectorで返す void findSameValueVertival(const cv::Mat& src, std::vector<Range>& ranges) { //積分画像が欲しい CV_Assert(src.type() == CV_32SC1); //値が入っているかもしれないので空にする ranges.clear(); Range range; const int endPos = src.cols - 1; int src0 = src.ptr<int>(0)[endPos]; int src1 = src.ptr<int>(1)[endPos]; if (src0 == src1){ range.start = 0; } src0 = src1; for (int i = 1; i < src.rows; i++){ src1 = src.ptr<int>(i)[endPos]; //上隣と同じ値 bool sameValue = src0 == src1; //左隣と同じ値 かつ 範囲のstartが初期値(-1)のとき if (sameValue && range.start < 0){ //文字のない範囲の始まり range.start = i - 1; } //左隣と違う値 かつ 範囲のstartが代入済み else if (!sameValue && range.start >= 0){ //文字のない範囲の終わり range.end = i - 1; //結果として保存 ranges.push_back(range); //文字のない範囲を初期値に戻す range.start = -1; range.end = -1; } src0 = src1; } //最後の範囲が画像の右端まである場合はfor文を抜けてから結果を保存する //文字のない範囲のstartは代入済み かつ 範囲のendは初期値のとき if (range.start >= 0 && range.end < 0){ range.end = src.cols - 1; ranges.push_back(range); } } int main(int argc, char** argv) { #ifndef _DEBUG //コマンドライン引数の解析。デバッグの時は使わない string commandArgs = "@input | | processing one image or image named serial number" ; cv::CommandLineParser parser(argc, argv, commandArgs); string src = parser.get<string>(0); #else string src = TEST_DATA_0; #endif cout << "input file:" << src << endl; //画像の読み込み。グレースケール画像として読み込む cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE); CV_Assert(image.channels() == 1 && image.type() == CV_8UC1); showImage(image); //二値化 cv::Mat binary; int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。 int binaryThreshold = 128; cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV); CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1); showImage(binary); cv::imwrite("binary.jpg", binary); //積分画像の生成 cv::Mat integral; cv::integral(binary, integral); CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1); showImage(integral); cv::imwrite("integral.jpg", integral); //積分画像を見やすくする処理 cv::Mat integralVisible; double max; double min; cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う CV_Assert(min == 0.0);//本当に最小値が0になっているか確認 integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。 showImage(integralVisible); cv::imwrite("integralVisible.jpg", integralVisible); //横方向 //文字のない範囲を受け取る変数 vector<Range> horizontalRanges; findSameValueHorizontal(integral, horizontalRanges); //文字のない範囲を書き込む画像 cv::Mat horizontalRangeDst; //1チャンネルの原画像から3チャンネルの画像を作る cv::Mat srcArray[] = {image, image, image}; cv::merge(srcArray, 3, horizontalRangeDst); //文字のない範囲を3チャンネルの原画像に書き込む for (size_t i = 0; i < horizontalRanges.size(); i++){ Range& r = horizontalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(r.start, 0, r.end - r.start + 1, horizontalRangeDst.rows); cv::Mat roi(horizontalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(240, 176, 0); } showImage(horizontalRangeDst); cv::imwrite("horizontalDst.jpg", horizontalRangeDst); //縦方向 //文字のない範囲を受け取る変数 vector<Range> verticalRanges; findSameValueVertival(integral, verticalRanges); //文字のない範囲を書き込む画像 cv::Mat verticalRangeDst; //1チャンネルの原画像から3チャンネルの画像を作る cv::merge(srcArray, 3, verticalRangeDst); //文字のない範囲を3チャンネルの原画像に書き込む for (size_t i = 0; i < verticalRanges.size(); i++){ Range& r = verticalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(0, r.start, verticalRangeDst.cols, r.end - r.start + 1); cv::Mat roi(verticalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(0, 0, 255); } showImage(verticalRangeDst); cv::imwrite("verticalDst.jpg", verticalRangeDst); //横方向の結果と縦方向の結果を合わせる for (size_t i = 0; i < verticalRanges.size(); i++){ Range& r = verticalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(0, r.start, horizontalRangeDst.cols, r.end - r.start + 1); cv::Mat roi(horizontalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(0, 0, 255); } showImage(horizontalRangeDst); cv::imwrite("horizontalVerticalDst.jpg", verticalRangeDst); }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////// // This file is part of Grappa, a system for scaling irregular // applications on commodity clusters. // Copyright (C) 2010-2014 University of Washington and Battelle // Memorial Institute. University of Washington authorizes use of this // Grappa software. // Grappa is free software: you can redistribute it and/or modify it // under the terms of the Affero General Public License as published // by Affero, Inc., either version 1 of the License, or (at your // option) any later version. // Grappa 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 // Affero General Public License for more details. // You should have received a copy of the Affero General Public // License along with this program. If not, you may obtain one from // http://www.affero.org/oagpl.html. //////////////////////////////////////////////////////////////////////// #pragma once #include <Collective.hpp> #include <functional> /// /// A Reducer object encapsulates a reduction /// during the computation to a single location /// /// Warning: may only use one object of type AllReducer<T, ReduceOp> /// concurrently because relies on `Grappa::allreduce`, /// which has no way of tagging messages /// template <typename T, T (*ReduceOp)(const T&, const T&)> class AllReducer { private: T localSum; bool finished; const T init; public: AllReducer(T init) : init(init) {} void reset() { finished = false; localSum = init; } void accumulate(T val) { localSum = ReduceOp(localSum, val); } /// Finish the reduction and return the final value. /// This must not be called until all corresponding /// local reduction objects have been finished and /// synchronized externally. /// /// ALLCORES T finish() { if (!finished) { finished = true; //TODO init version and specialized version for non-template allowed localSum = Grappa::allreduce<T,ReduceOp> (localSum); } return localSum; } //TODO, a non collective call to finish would be nice //any such scheme will require knowing where each participant's //value lives (e.g. process-global variable) }; namespace Grappa { /// @brief Symmetric Reduction object template< typename T > class SimpleSymmetric { T local_value; // GlobalAddress<SimpleSymmetric> self; public: SimpleSymmetric(): local_value() {} T& local() { return local_value; } const T& local() const { return local_value; } // static GlobalAddress<SimpleSymmetric> create() { // auto s = symmetric_global_alloc<SimpleSymmetric>(); // call_on_all_cores([s]{ // s->self = s; // }); // } friend T all(SimpleSymmetric * r) { return reduce<T,collective_and>(&r->local_value); } friend T any(SimpleSymmetric * r) { return reduce<T,collective_or >(&r->local_value); } friend T sum(SimpleSymmetric * r) { return reduce<T,collective_add>(&r->local_value); } friend void set(SimpleSymmetric * r, const T& val) { call_on_all_cores([=]{ r->local_value = val; }); } friend T all(SimpleSymmetric& r) { return all(&r); } friend T any(SimpleSymmetric& r) { return any(&r); } friend T sum(SimpleSymmetric& r) { return sum(&r); } friend void set(SimpleSymmetric& r, const T& val) { return set(&r, val); } void operator|=(const T& val) { local() |= val; } void operator+=(const T& val) { local() += val; } void operator++() { local()++; } void operator++(int) { local()++; } } GRAPPA_BLOCK_ALIGNED; template< typename T, T (*ReduceOp)(const T&, const T&) > class ReducerBase { protected: T local_value; public: ReducerBase(): local_value() {} /// Read out value; does expensive global reduce. /// /// Called implicitly when the Reducer is used as the underlying type, /// or by an explicit cast operation. operator T () const { return reduce<T,ReduceOp>(&this->local_value); } /// Globally set the value; expensive global synchronization. void operator=(const T& v){ reset(); local_value = v; } /// Globally reset to default value for the type. void reset() { call_on_all_cores([this]{ this->local_value = T(); }); } }; #define Super(...) \ using Super = __VA_ARGS__; \ using Super::operator=; \ using Super::reset enum class ReducerType { Add, Or, And, Max, Min }; /// Reducers are a special kind of *symmetric* object that, when read, /// compute a reduction over all instances. They can be inexpensively updated /// (incremented/decremented, etc), so operations that modify the value /// without observing it are cheap and require no communication. However, /// reading the value forces a global reduction operation each time, /// and directly setting the value forces global synchronization. /// /// *Reducers must be declared in the C++ global scope* ("global variables") /// so they have identical pointers on each core. Declaring one as a local /// variable (on the stack), or in a symmetric allocation will lead to /// segfaults or worse. /// /// By default, Reducers do a global "sum", using the `+` operator; other /// operations can be specified by ReducerType (second template parameter). /// /// Example usage (count non-negative values in an array): /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// // declare symmetric global object /// Reducer<int> non_negative_count; /// /// int main(int argc, char* argv[]) { /// Grappa::init(&argc, &argv); /// Grappa::run([]{ /// GlobalAddress<double> A; /// // allocate & initialize array A... /// /// // set global count to 0 (expensive global sync.) /// non_negative_count = 0; /// /// forall(A, N, [](double& A_i){ /// if (A_i > 0) { /// // cheap local increment /// non_negative_count += 1; /// } /// }); /// /// // read out total value and print it (expensive global reduction) /// LOG(INFO) << non_negative_count << " non negative values"; /// }); /// Grappa::finalize(); /// } /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T, ReducerType R > class Reducer : public ReducerBase<T,collective_add> {}; /// Reducer for sum (+), useful for global accumulators. /// Provides cheap operators for increment and decrement /// (`++`, `+=`, `--`, `-=`). template< typename T > class Reducer<T,ReducerType::Add> : public ReducerBase<T,collective_add> { public: Super(ReducerBase<T,collective_add>); void operator+=(const T& v){ this->local_value += v; } void operator++(){ this->local_value++; } void operator++(int){ this->local_value++; } void operator-=(const T& v){ this->local_value -= v; } void operator--(){ this->local_value--; } void operator--(int){ this->local_value--; } }; /// Reducer for "or" (`operator|`). /// Useful for "any" checks, such as "are any values non-zero?". /// Provides cheap operator for "or-ing" something onto the value: `|=`. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<bool,ReducerType::Or> any_nonzero; /// /// // ... (somewhere in main task) /// any_nonzero = false; /// forall(A, N, [](double& A_i){ /// if (A_i != 0) { /// any_nonzero |= true /// } /// }); /// LOG(INFO) << ( any_nonzero ? "some" : "no" ) << " nonzeroes."; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Or> : public ReducerBase<T,collective_or> { public: Super(ReducerBase<T,collective_or>); void operator|=(const T& v){ this->local_value |= v; } }; /// Reducer for "and" (`operator&`). /// Useful for "all" checks, such as "are all values non-zero?". /// Provides cheap operator for "and-ing" something onto the value: `&=`. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<bool,ReducerType::And> all_nonzero; /// /// // ... (somewhere in main task) /// all_zero = true; /// forall(A, N, [](double& A_i){ /// all_zero &= (A_i == 0); /// }); /// LOG(INFO) << ( all_zero ? "" : "not " ) << "all zero."; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::And> : public ReducerBase<T,collective_and> { public: Super(ReducerBase<T,collective_and>); void operator&=(const T& v){ this->local_value &= v; } }; /// Reducer for finding the maximum of many values. /// Provides cheap operator (`<<`) for "inserting" potential max values. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<double,ReducerType::Max> max_val; /// /// // ... (somewhere in main task) /// max_val = 0.0; /// forall(A, N, [](double& A_i){ /// max_val << A_i; /// }); /// LOG(INFO) << "maximum value: " << max_val; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Max> : public ReducerBase<T,collective_max> { public: Super(ReducerBase<T,collective_max>); void operator<<(const T& v){ if (v > this->local_value) { this->local_value = v; } } }; /// Reducer for finding the minimum of many values. /// Provides cheap operator (`<<`) for "inserting" potential min values. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<double,ReducerType::Min> min_val; /// /// // ... (somewhere in main task) /// min_val = 0.0; /// forall(A, N, [](double& A_i){ /// min_val << A_i; /// }); /// LOG(INFO) << "minimum value: " << min_val; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Min> : public ReducerBase<T,collective_min> { public: Super(ReducerBase<T,collective_min>); void operator<<(const T& v){ if (v < this->local_value) { this->local_value = v; } } }; #undef Super /// Helper class for implementing reduceable tuples, where reduce is based on /// just one of the two elements /// /// Example usage to find the vertex with maximum degree in a graph (from SSSP app): /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// using MaxDegree = CmpElement<VertexID,int64_t>; /// Reducer<MaxDegree,ReducerType::Max> max_degree; /// /// ... /// GlobalAddress<G> g; /// // ...initialize graph structure... /// /// // find max degree vertex /// forall(g, [](VertexID i, G::Vertex& v){ /// max_degree << MaxDegree(i, v.nadj); /// }); /// root = static_cast<MaxDegree>(max_degree).idx(); /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename Id, typename Cmp > class CmpElement { Id i; Cmp c; public: CmpElement(): i(), c() {} CmpElement(Id i, Cmp c): i(i), c(c) {} Id idx() const { return i; } Cmp elem() const { return c; } bool operator<(const CmpElement& e) const { return elem() < e.elem(); } bool operator>(const CmpElement& e) const { return elem() > e.elem(); } }; } // namespace Grappa<commit_msg>document SimpleSymmetric<commit_after>//////////////////////////////////////////////////////////////////////// // This file is part of Grappa, a system for scaling irregular // applications on commodity clusters. // Copyright (C) 2010-2014 University of Washington and Battelle // Memorial Institute. University of Washington authorizes use of this // Grappa software. // Grappa is free software: you can redistribute it and/or modify it // under the terms of the Affero General Public License as published // by Affero, Inc., either version 1 of the License, or (at your // option) any later version. // Grappa 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 // Affero General Public License for more details. // You should have received a copy of the Affero General Public // License along with this program. If not, you may obtain one from // http://www.affero.org/oagpl.html. //////////////////////////////////////////////////////////////////////// #pragma once #include <Collective.hpp> #include <functional> /// /// A Reducer object encapsulates a reduction /// during the computation to a single location /// /// Warning: may only use one object of type AllReducer<T, ReduceOp> /// concurrently because relies on `Grappa::allreduce`, /// which has no way of tagging messages /// template <typename T, T (*ReduceOp)(const T&, const T&)> class AllReducer { private: T localSum; bool finished; const T init; public: AllReducer(T init) : init(init) {} void reset() { finished = false; localSum = init; } void accumulate(T val) { localSum = ReduceOp(localSum, val); } /// Finish the reduction and return the final value. /// This must not be called until all corresponding /// local reduction objects have been finished and /// synchronized externally. /// /// ALLCORES T finish() { if (!finished) { finished = true; //TODO init version and specialized version for non-template allowed localSum = Grappa::allreduce<T,ReduceOp> (localSum); } return localSum; } //TODO, a non collective call to finish would be nice //any such scheme will require knowing where each participant's //value lives (e.g. process-global variable) }; namespace Grappa { /// Symmetric object with no special built-in semantics, but several /// reduction-oriented operations defined. /// /// Intended to be used as a building block for symmetric objects or /// when manual management of reductions on symmetric data. /// /// This is closely related to Reducer, but rather than implicitly performing /// reduction operations whenever the value is observed, SimpleSymmetric's /// require one of the helper reducer operations to be applied manually. This /// flexibility could be useful for doing more than one kind of reduction on /// the same symmetric object. /// /// Example usage for a global counter: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// SimpleSymmetric<int> global_x; /// /// // ... /// Grappa::run([]{ /// GlobalAddress<int> A = /* initialize array A */; /// /// // increment counter locally /// forall(A, N, [](int& A_i){ if (A_i == 0) global_x++; }); /// /// // compute reduction explicitly to get total /// int total = sum(global_x); /// /// }); /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// Or to use it for global boolean checks: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// SimpleSymmetric<bool> x; /// /// // ... /// Grappa::run([]{ /// GlobalAddress<int> A = /* initialize array A */; /// /// // initialize x on all cores to false /// set(x, false); /// /// // find if all elements are > 0 (and's all symmetric bools together) /// forall(A, N, [](int& A_i){ if (A_i > 0) x &= true; }); /// bool all_postive = all(x); /// /// // find if any are negative (or's all symmetric bools together) /// set(x, false); /// forall(A, N, [](int& A_i){ if (A_i < 0) x = true; }); /// bool any_negative = any(x); /// /// }); /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class SimpleSymmetric { T local_value; // GlobalAddress<SimpleSymmetric> self; public: SimpleSymmetric(): local_value() {} T& local() { return local_value; } const T& local() const { return local_value; } // static GlobalAddress<SimpleSymmetric> create() { // auto s = symmetric_global_alloc<SimpleSymmetric>(); // call_on_all_cores([s]{ // s->self = s; // }); // } /// Reduction across symmetric object doing 'and' ('&') friend T all(SimpleSymmetric * r) { return reduce<T,collective_and>(&r->local_value); } /// Reduction across symmetric object doing 'or' ('|') friend T any(SimpleSymmetric * r) { return reduce<T,collective_or >(&r->local_value); } /// Reduction across symmetric object doing 'sum' ('+') friend T sum(SimpleSymmetric * r) { return reduce<T,collective_add>(&r->local_value); } /// Set instances on all cores to the given value. friend void set(SimpleSymmetric * r, const T& val) { call_on_all_cores([=]{ r->local_value = val; }); } /// Reduction across symmetric object doing 'and' ('&') friend T all(SimpleSymmetric& r) { return all(&r); } /// Reduction across symmetric object doing 'or' ('|') friend T any(SimpleSymmetric& r) { return any(&r); } /// Reduction across symmetric object doing 'sum' ('+') friend T sum(SimpleSymmetric& r) { return sum(&r); } /// Set instances on all cores to the given value. friend void set(SimpleSymmetric& r, const T& val) { return set(&r, val); } /// Operate on local copy. T& operator&=(const T& val) { return local() &= val; } /// Operate on local copy. T& operator|=(const T& val) { return local() |= val; } /// Operate on local copy. T& operator+=(const T& val) { return local() += val; } /// Operate on local copy. T& operator++() { return ++local(); } /// Operate on local copy. T& operator++(int) { return local()++; } } GRAPPA_BLOCK_ALIGNED; /// Base class for Reducer implementing some operations common to all /// specializations. template< typename T, T (*ReduceOp)(const T&, const T&) > class ReducerImpl { protected: T local_value; public: ReducerImpl(): local_value() {} /// Read out value; does expensive global reduce. /// /// Called implicitly when the Reducer is used as the underlying type, /// or by an explicit cast operation. operator T () const { return reduce<T,ReduceOp>(&this->local_value); } /// Globally set the value; expensive global synchronization. void operator=(const T& v){ reset(); local_value = v; } /// Globally reset to default value for the type. void reset() { call_on_all_cores([this]{ this->local_value = T(); }); } }; #define Super(...) \ using Super = __VA_ARGS__; \ using Super::operator=; \ using Super::reset enum class ReducerType { Add, Or, And, Max, Min }; /// Reducers are a special kind of *symmetric* object that, when read, /// compute a reduction over all instances. They can be inexpensively updated /// (incremented/decremented, etc), so operations that modify the value /// without observing it are cheap and require no communication. However, /// reading the value forces a global reduction operation each time, /// and directly setting the value forces global synchronization. /// /// *Reducers must be declared in the C++ global scope* ("global variables") /// so they have identical pointers on each core. Declaring one as a local /// variable (on the stack), or in a symmetric allocation will lead to /// segfaults or worse. /// /// By default, Reducers do a global "sum", using the `+` operator; other /// operations can be specified by ReducerType (second template parameter). /// /// Example usage (count non-negative values in an array): /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// // declare symmetric global object /// Reducer<int> non_negative_count; /// /// int main(int argc, char* argv[]) { /// Grappa::init(&argc, &argv); /// Grappa::run([]{ /// GlobalAddress<double> A; /// // allocate & initialize array A... /// /// // set global count to 0 (expensive global sync.) /// non_negative_count = 0; /// /// forall(A, N, [](double& A_i){ /// if (A_i > 0) { /// // cheap local increment /// non_negative_count += 1; /// } /// }); /// /// // read out total value and print it (expensive global reduction) /// LOG(INFO) << non_negative_count << " non negative values"; /// }); /// Grappa::finalize(); /// } /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T, ReducerType R > class Reducer : public ReducerImpl<T,collective_add> {}; /// Reducer for sum (+), useful for global accumulators. /// Provides cheap operators for increment and decrement /// (`++`, `+=`, `--`, `-=`). template< typename T > class Reducer<T,ReducerType::Add> : public ReducerImpl<T,collective_add> { public: Super(ReducerImpl<T,collective_add>); void operator+=(const T& v){ this->local_value += v; } void operator++(){ this->local_value++; } void operator++(int){ this->local_value++; } void operator-=(const T& v){ this->local_value -= v; } void operator--(){ this->local_value--; } void operator--(int){ this->local_value--; } }; /// Reducer for "or" (`operator|`). /// Useful for "any" checks, such as "are any values non-zero?". /// Provides cheap operator for "or-ing" something onto the value: `|=`. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<bool,ReducerType::Or> any_nonzero; /// /// // ... (somewhere in main task) /// any_nonzero = false; /// forall(A, N, [](double& A_i){ /// if (A_i != 0) { /// any_nonzero |= true /// } /// }); /// LOG(INFO) << ( any_nonzero ? "some" : "no" ) << " nonzeroes."; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Or> : public ReducerImpl<T,collective_or> { public: Super(ReducerImpl<T,collective_or>); void operator|=(const T& v){ this->local_value |= v; } }; /// Reducer for "and" (`operator&`). /// Useful for "all" checks, such as "are all values non-zero?". /// Provides cheap operator for "and-ing" something onto the value: `&=`. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<bool,ReducerType::And> all_nonzero; /// /// // ... (somewhere in main task) /// all_zero = true; /// forall(A, N, [](double& A_i){ /// all_zero &= (A_i == 0); /// }); /// LOG(INFO) << ( all_zero ? "" : "not " ) << "all zero."; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::And> : public ReducerImpl<T,collective_and> { public: Super(ReducerImpl<T,collective_and>); void operator&=(const T& v){ this->local_value &= v; } }; /// Reducer for finding the maximum of many values. /// Provides cheap operator (`<<`) for "inserting" potential max values. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<double,ReducerType::Max> max_val; /// /// // ... (somewhere in main task) /// max_val = 0.0; /// forall(A, N, [](double& A_i){ /// max_val << A_i; /// }); /// LOG(INFO) << "maximum value: " << max_val; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Max> : public ReducerImpl<T,collective_max> { public: Super(ReducerImpl<T,collective_max>); void operator<<(const T& v){ if (v > this->local_value) { this->local_value = v; } } }; /// Reducer for finding the minimum of many values. /// Provides cheap operator (`<<`) for "inserting" potential min values. /// /// Example: /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// Reducer<double,ReducerType::Min> min_val; /// /// // ... (somewhere in main task) /// min_val = 0.0; /// forall(A, N, [](double& A_i){ /// min_val << A_i; /// }); /// LOG(INFO) << "minimum value: " << min_val; /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename T > class Reducer<T,ReducerType::Min> : public ReducerImpl<T,collective_min> { public: Super(ReducerImpl<T,collective_min>); void operator<<(const T& v){ if (v < this->local_value) { this->local_value = v; } } }; #undef Super /// Helper class for implementing reduceable tuples, where reduce is based on /// just one of the two elements /// /// Example usage to find the vertex with maximum degree in a graph (from SSSP app): /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// using MaxDegree = CmpElement<VertexID,int64_t>; /// Reducer<MaxDegree,ReducerType::Max> max_degree; /// /// ... /// GlobalAddress<G> g; /// // ...initialize graph structure... /// /// // find max degree vertex /// forall(g, [](VertexID i, G::Vertex& v){ /// max_degree << MaxDegree(i, v.nadj); /// }); /// root = static_cast<MaxDegree>(max_degree).idx(); /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ template< typename Id, typename Cmp > class CmpElement { Id i; Cmp c; public: CmpElement(): i(), c() {} CmpElement(Id i, Cmp c): i(i), c(c) {} Id idx() const { return i; } Cmp elem() const { return c; } bool operator<(const CmpElement& e) const { return elem() < e.elem(); } bool operator>(const CmpElement& e) const { return elem() > e.elem(); } }; } // namespace Grappa<|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // path temp_directory_path(); // path temp_directory_path(error_code& ec); #include <experimental/filesystem> #include <memory> #include <cstdlib> #include <cstring> #include <cassert> #include "test_macros.h" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" using namespace std::experimental::filesystem; void PutEnv(std::string var, std::string value) { assert(::setenv(var.c_str(), value.c_str(), /* overwrite */ 1) == 0); } void UnsetEnv(std::string var) { assert(::unsetenv(var.c_str()) == 0); } TEST_SUITE(filesystem_temp_directory_path_test_suite) TEST_CASE(signature_test) { std::error_code ec; ((void)ec); ASSERT_NOT_NOEXCEPT(temp_directory_path()); ASSERT_NOT_NOEXCEPT(temp_directory_path(ec)); } TEST_CASE(basic_tests) { scoped_test_env env; const path dne = env.make_env_path("dne"); const path file = env.create_file("file", 42); const path dir_perms = env.create_dir("bad_perms_dir"); const path nested_dir = env.create_dir("bad_perms_dir/nested"); permissions(dir_perms, perms::none); const std::error_code set_ec = std::make_error_code(std::errc::address_in_use); const std::error_code expect_ec = std::make_error_code(std::errc::not_a_directory); struct TestCase { std::string name; path p; } cases[] = { {"TMPDIR", env.create_dir("dir1")}, {"TMP", env.create_dir("dir2")}, {"TEMP", env.create_dir("dir3")}, {"TEMPDIR", env.create_dir("dir4")} }; for (auto& TC : cases) { PutEnv(TC.name, TC.p); } for (auto& TC : cases) { std::error_code ec = set_ec; path ret = temp_directory_path(ec); TEST_CHECK(!ec); TEST_CHECK(ret == TC.p); TEST_CHECK(is_directory(ret)); // Set the env variable to a path that does not exist and check // that it fails. PutEnv(TC.name, dne); ec = set_ec; ret = temp_directory_path(ec); TEST_CHECK(ec == expect_ec); TEST_CHECK(ret == ""); // Set the env variable to point to a file and check that it fails. PutEnv(TC.name, file); ec = set_ec; ret = temp_directory_path(ec); TEST_CHECK(ec == expect_ec); TEST_CHECK(ret == ""); // Set the env variable to point to a dir we can't access PutEnv(TC.name, nested_dir); ec = set_ec; ret = temp_directory_path(ec); TEST_CHECK(ec == std::make_error_code(std::errc::permission_denied)); TEST_CHECK(ret == ""); // Finally erase this env variable UnsetEnv(TC.name); } // No env variables are defined { std::error_code ec = set_ec; path ret = temp_directory_path(ec); TEST_CHECK(!ec); TEST_CHECK(ret == "/tmp"); TEST_CHECK(is_directory(ret)); } } TEST_SUITE_END() <commit_msg>Fix non-portable tests for temp_directory_path(...)<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // path temp_directory_path(); // path temp_directory_path(error_code& ec); #include <experimental/filesystem> #include <memory> #include <cstdlib> #include <cstring> #include <cassert> #include "test_macros.h" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" using namespace std::experimental::filesystem; void PutEnv(std::string var, std::string value) { assert(::setenv(var.c_str(), value.c_str(), /* overwrite */ 1) == 0); } void UnsetEnv(std::string var) { assert(::unsetenv(var.c_str()) == 0); } TEST_SUITE(filesystem_temp_directory_path_test_suite) TEST_CASE(signature_test) { std::error_code ec; ((void)ec); ASSERT_NOT_NOEXCEPT(temp_directory_path()); ASSERT_NOT_NOEXCEPT(temp_directory_path(ec)); } TEST_CASE(basic_tests) { scoped_test_env env; const path dne = env.make_env_path("dne"); const path file = env.create_file("file", 42); const path dir_perms = env.create_dir("bad_perms_dir"); const path nested_dir = env.create_dir("bad_perms_dir/nested"); permissions(dir_perms, perms::none); const std::error_code expect_ec = std::make_error_code(std::errc::not_a_directory); struct TestCase { std::string name; path p; } cases[] = { {"TMPDIR", env.create_dir("dir1")}, {"TMP", env.create_dir("dir2")}, {"TEMP", env.create_dir("dir3")}, {"TEMPDIR", env.create_dir("dir4")} }; for (auto& TC : cases) { PutEnv(TC.name, TC.p); } for (auto& TC : cases) { std::error_code ec = GetTestEC(); path ret = temp_directory_path(ec); TEST_CHECK(!ec); TEST_CHECK(ret == TC.p); TEST_CHECK(is_directory(ret)); // Set the env variable to a path that does not exist and check // that it fails. PutEnv(TC.name, dne); ec = GetTestEC(); ret = temp_directory_path(ec); LIBCPP_ONLY(TEST_CHECK(ec == expect_ec)); TEST_CHECK(ec != GetTestEC()); TEST_CHECK(ec); TEST_CHECK(ret == ""); // Set the env variable to point to a file and check that it fails. PutEnv(TC.name, file); ec = GetTestEC(); ret = temp_directory_path(ec); LIBCPP_ONLY(TEST_CHECK(ec == expect_ec)); TEST_CHECK(ec != GetTestEC()); TEST_CHECK(ec); TEST_CHECK(ret == ""); // Set the env variable to point to a dir we can't access PutEnv(TC.name, nested_dir); ec = GetTestEC(); ret = temp_directory_path(ec); TEST_CHECK(ec == std::make_error_code(std::errc::permission_denied)); TEST_CHECK(ret == ""); // Finally erase this env variable UnsetEnv(TC.name); } // No env variables are defined { std::error_code ec = GetTestEC(); path ret = temp_directory_path(ec); TEST_CHECK(!ec); TEST_CHECK(ret == "/tmp"); TEST_CHECK(is_directory(ret)); } } TEST_SUITE_END() <|endoftext|>
<commit_before>/* test.c * * Test program: Various info about DOS * (C) 2009-2012 Jonathan Campbell. * Hackipedia DOS library. * * This code is licensed under the LGPL. * <insert LGPL legal text here> */ #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <stdio.h> #include <conio.h> #include <fcntl.h> #include <dos.h> int main() { printf("Hello world\n"); return 0; } <commit_msg>C++ fixup<commit_after> #include <stdio.h> int main() { printf("Hello world\n"); return 0; } <|endoftext|>
<commit_before>#ifndef JARNGREIPR_GEOMETRY_CENTER #define JARNGREIPR_GEOMETRY_CENTER #include <jarngreipr/model/Bead.hpp> #include <jarngreipr/io/PDBAtom.hpp> #include <jarngreipr/io/PDBResidue.hpp> #include <jarngreipr/io/PDBChain.hpp> #include <mjolnir/util/scalar_type_of.hpp> namespace mjolnir { template<typename coordT> inline coordT center(const Bead<coordT>& bead) { return bead.position(); } template<typename coordT> coordT center(const std::vector<Bead<coordT>>& beads) { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& bead : beads) { pos += bead.position(); } return pos / static_cast<real_type>(beads.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const std::vector<Bead<coordT>>& beads, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& bead : beads) { if(satisfy(bead)) { pos += bead.position(); ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> inline coordT center(const PDBAtom<coordT>& atom) noexcept { return atom.position; } template<typename coordT> coordT center(const std::vector<PDBAtom<coordT>>& atoms) noexcept { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& atom : atoms) { pos += atom.position; } return pos / static_cast<real_type>(atoms.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const std::vector<PDBAtom<coordT>>& atoms, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& atom : atoms) { if(satisfy(atom)) { pos += atom.position; ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> coordT center(const PDBResidue<coordT>& residue) noexcept { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& atom : residue) { pos += atom.position; } return pos / static_cast<real_type>(residue.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const PDBResidue<coordT>& residue, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& atom : residue) { if(satisfy(atom)) { pos += atom.position; ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> coordT center(const PDBChain<coordT>& chain) noexcept { typedef typename scalar_type_of<coordT>::type real_type; std::size_t num_p = 0; coordT pos(0,0,0); for(const auto& residue : chain) { for(const auto& atom : residue) { pos += atom.position; ++num_p; } } return pos / static_cast<real_type>(num_p); } template<typename coordT, typename UnaryPredicate> coordT center_if(const PDBChain<coordT>& chain, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t num_p = 0; coordT pos(0,0,0); for(const auto& residue : chain) { for(const auto& atom : residue) { if(satisfy(atom)) { pos += atom.position; ++num_p; } } } return pos / static_cast<real_type>(num_p); } template<typename Iterator> inline typename std::iterator_traits<Iterator>::value_type::coord_type center(Iterator first, const Iterator last) noexcept { typedef typename std::iterator_traits<Iterator>::value_type::coord_type coord_type; typedef typename coord_type::real_type real_type; std::size_t num_p = 0; coord_type pos(0,0,0); for(; first != last; ++first) { pos += center(*first); ++num_p; } return pos / static_cast<real_type>(num_p); } } // mjolnir #endif// JARNGREIPR_GEOMETRY_CENTER <commit_msg>rename coord_type -> coordinate_type<commit_after>#ifndef JARNGREIPR_GEOMETRY_CENTER #define JARNGREIPR_GEOMETRY_CENTER #include <jarngreipr/model/Bead.hpp> #include <jarngreipr/io/PDBAtom.hpp> #include <jarngreipr/io/PDBResidue.hpp> #include <jarngreipr/io/PDBChain.hpp> #include <mjolnir/util/scalar_type_of.hpp> namespace mjolnir { template<typename coordT> inline coordT center(const Bead<coordT>& bead) { return bead.position(); } template<typename coordT> coordT center(const std::vector<Bead<coordT>>& beads) { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& bead : beads) { pos += bead.position(); } return pos / static_cast<real_type>(beads.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const std::vector<Bead<coordT>>& beads, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& bead : beads) { if(satisfy(bead)) { pos += bead.position(); ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> inline coordT center(const PDBAtom<coordT>& atom) noexcept { return atom.position; } template<typename coordT> coordT center(const std::vector<PDBAtom<coordT>>& atoms) noexcept { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& atom : atoms) { pos += atom.position; } return pos / static_cast<real_type>(atoms.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const std::vector<PDBAtom<coordT>>& atoms, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& atom : atoms) { if(satisfy(atom)) { pos += atom.position; ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> coordT center(const PDBResidue<coordT>& residue) noexcept { typedef typename scalar_type_of<coordT>::type real_type; coordT pos(0,0,0); for(const auto& atom : residue) { pos += atom.position; } return pos / static_cast<real_type>(residue.size()); } template<typename coordT, typename UnaryPredicate> coordT center_if(const PDBResidue<coordT>& residue, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t N = 0; coordT pos(0,0,0); for(const auto& atom : residue) { if(satisfy(atom)) { pos += atom.position; ++N; } } return pos / static_cast<real_type>(N); } template<typename coordT> coordT center(const PDBChain<coordT>& chain) noexcept { typedef typename scalar_type_of<coordT>::type real_type; std::size_t num_p = 0; coordT pos(0,0,0); for(const auto& residue : chain) { for(const auto& atom : residue) { pos += atom.position; ++num_p; } } return pos / static_cast<real_type>(num_p); } template<typename coordT, typename UnaryPredicate> coordT center_if(const PDBChain<coordT>& chain, UnaryPredicate&& satisfy) { typedef typename scalar_type_of<coordT>::type real_type; std::size_t num_p = 0; coordT pos(0,0,0); for(const auto& residue : chain) { for(const auto& atom : residue) { if(satisfy(atom)) { pos += atom.position; ++num_p; } } } return pos / static_cast<real_type>(num_p); } template<typename Iterator> inline typename std::iterator_traits<Iterator>::value_type::coordinate_type center(Iterator first, const Iterator last) noexcept { typedef typename std::iterator_traits<Iterator>::value_type::coordinate_type coordinate_type; typedef typename coordinate_type::real_type real_type; std::size_t num_p = 0; coordinate_type pos(0,0,0); for(; first != last; ++first) { pos += center(*first); ++num_p; } return pos / static_cast<real_type>(num_p); } } // mjolnir #endif// JARNGREIPR_GEOMETRY_CENTER <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP #define IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP #include "source/example_base_class.hpp" namespace example { /// @brief Short description /// @code /// minimalistic working example which uses all public methods /// @endcode /// @swcomponent example_component void someFreeFunction(); /// @brief Forward declaration of other class class SomeOtherClass; /// @brief Short description /// @details Detailed description /// @code /// /// @endcode /// @note Important note for user/developer /// @swcomponent cpp template <typename T> class MySampleClass : public ExampleBaseClass<T> { public: /// @brief Short description /// @details Detailed description /// @param[in] a Description of input parameter a /// @param[in] b Description of input parameter b MySampleClass(const int a, const int b) noexcept; /// @brief Short description void simpleMethod() const noexcept; /// @brief Short description /// @param[in] c Description of input parameter c /// @param[out] d Description of output parameter d /// @return Description of return value int complexMethod(const uint32_t c, const uint32_t* d) noexcept; /// @brief A good example method which sets some kind of speed /// @code /// myClass.goodExampleMethod(200_kmh); // sets it to 200 km/h /// myClass.goodExampleMethod(40_ms); // sets it to 40 m/s /// @endcode void goodExampleMethod(const speed_t speed) noexcept; /// @brief Short description /// @pre Must be called before another method is called /// @post Cannot be called twice, once it is called everything is done /// @param[in] fuu some clarification, min and max is also defined here /// and not specified with a custom tag. /// 0 <= fuu <= 1000 /// @deprecated remove when feature iox is done void preInitStuff(const uint32_t fuu) noexcept; }; } // namespace example #endif // IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP <commit_msg>iox-#198 rename sample class<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP #define IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP #include "source/example_base_class.hpp" namespace example { /// @brief Short description /// @code /// minimalistic working example which uses all public methods /// @endcode /// @swcomponent example_component void someFreeFunction(); /// @brief Forward declaration of other class class SomeOtherClass; /// @brief Short description /// @details Detailed description /// @code /// /// @endcode /// @note Important note for user/developer /// @swcomponent cpp template <typename T> class ExampleSampleClass : public ExampleBaseClass<T> { public: /// @brief Short description /// @details Detailed description /// @param[in] a Description of input parameter a /// @param[in] b Description of input parameter b ExampleSampleClass(const int a, const int b) noexcept; /// @brief Short description void simpleMethod() const noexcept; /// @brief Short description /// @param[in] c Description of input parameter c /// @param[out] d Description of output parameter d /// @return Description of return value int complexMethod(const uint32_t c, const uint32_t* d) noexcept; /// @brief A good example method which sets some kind of speed /// @code /// myClass.goodExampleMethod(200_kmh); // sets it to 200 km/h /// myClass.goodExampleMethod(40_ms); // sets it to 40 m/s /// @endcode void goodExampleMethod(const speed_t speed) noexcept; /// @brief Short description /// @pre Must be called before another method is called /// @post Cannot be called twice, once it is called everything is done /// @param[in] fuu some clarification, min and max is also defined here /// and not specified with a custom tag. /// 0 <= fuu <= 1000 /// @deprecated remove when feature iox is done void preInitStuff(const uint32_t fuu) noexcept; }; } // namespace example #endif // IOX_DOC_EXAMPLE_COMPONENT_EXAMPLE_SAMPLE_CLASS_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "rtc.hpp" #include "kernel_utils.hpp" namespace { #define CURRENT_YEAR 2013 #define cmos_address 0x70 #define cmos_data 0x71 int get_update_in_progress_flag(){ out_byte(cmos_address, 0x0A); return (in_byte(cmos_data) & 0x80); } uint8_t get_RTC_register(int reg){ out_byte(cmos_address, reg); return in_byte(cmos_data); } } //end of anonymous namespace datetime rtc::all_data(){ uint8_t second; uint8_t minute; uint8_t hour; uint8_t day; uint8_t month; uint8_t year; uint8_t last_second; uint8_t last_minute; uint8_t last_hour; uint8_t last_day; uint8_t last_month; uint8_t last_year; uint8_t registerB; //TODO When ACPI gets supported, get the address //of the century register and use it to make //better year calculation while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress second = get_RTC_register(0x00); minute = get_RTC_register(0x02); hour = get_RTC_register(0x04); day = get_RTC_register(0x07); month = get_RTC_register(0x08); year = get_RTC_register(0x09); do { last_second = second; last_minute = minute; last_hour = hour; last_day = day; last_month = month; last_year = year; while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress second = get_RTC_register(0x00); minute = get_RTC_register(0x02); hour = get_RTC_register(0x04); day = get_RTC_register(0x07); month = get_RTC_register(0x08); year = get_RTC_register(0x09); } while( (last_second != second) || (last_minute != minute) || (last_hour != hour) || (last_day != day) || (last_month != month) || (last_year != year) ); registerB = get_RTC_register(0x0B); // Convert BCD to binary values if necessary if (!(registerB & 0x04)) { second = (second & 0x0F) + ((second / 16) * 10); minute = (minute & 0x0F) + ((minute / 16) * 10); hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); day = (day & 0x0F) + ((day / 16) * 10); month = (month & 0x0F) + ((month / 16) * 10); year = (year & 0x0F) + ((year / 16) * 10); } // Convert 12 hour clock to 24 hour clock if necessary if (!(registerB & 0x02) && (hour & 0x80)) { hour = ((hour & 0x7F) + 12) % 24; } // Calculate the full (4-digit) year uint16_t full_year = year + (CURRENT_YEAR / 100) * 100; if(full_year < CURRENT_YEAR){ full_year += 100; } return {full_year, month, day, hour, minute, second, 0, 0}; } <commit_msg>Use the century register when available<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "rtc.hpp" #include "kernel_utils.hpp" #include "acpi.hpp" #include "acpica.hpp" #include "logging.hpp" namespace { constexpr const size_t FADT2_REVISION_ID = 3; #define CURRENT_YEAR 2013 #define cmos_address 0x70 #define cmos_data 0x71 int get_update_in_progress_flag(){ out_byte(cmos_address, 0x0A); return (in_byte(cmos_data) & 0x80); } uint8_t get_RTC_register(int reg){ out_byte(cmos_address, reg); return in_byte(cmos_data); } } //end of anonymous namespace datetime rtc::all_data(){ uint8_t second; uint8_t minute; uint8_t hour; uint8_t day; uint8_t month; uint8_t year; uint8_t century = 0x0; uint8_t last_second; uint8_t last_minute; uint8_t last_hour; uint8_t last_day; uint8_t last_month; uint8_t last_year; uint8_t last_century; uint8_t registerB; int century_register = 0x0; if (acpi::initialized() && AcpiGbl_FADT.Header.Revision >= FADT2_REVISION_ID && AcpiGbl_FADT.Century){ century_register = AcpiGbl_FADT.Century; } while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress second = get_RTC_register(0x00); minute = get_RTC_register(0x02); hour = get_RTC_register(0x04); day = get_RTC_register(0x07); month = get_RTC_register(0x08); year = get_RTC_register(0x09); if(century_register){ century = get_RTC_register(century_register); } do { last_second = second; last_minute = minute; last_hour = hour; last_day = day; last_month = month; last_year = year; last_century = century; while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress second = get_RTC_register(0x00); minute = get_RTC_register(0x02); hour = get_RTC_register(0x04); day = get_RTC_register(0x07); month = get_RTC_register(0x08); year = get_RTC_register(0x09); if(century_register){ century = get_RTC_register(century_register); } } while( (last_second != second) || (last_minute != minute) || (last_hour != hour) || (last_day != day) || (last_month != month) || (last_year != year) || (last_century != century)); registerB = get_RTC_register(0x0B); // Convert BCD to binary values if necessary if (!(registerB & 0x04)) { second = (second & 0x0F) + ((second / 16) * 10); minute = (minute & 0x0F) + ((minute / 16) * 10); hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); day = (day & 0x0F) + ((day / 16) * 10); month = (month & 0x0F) + ((month / 16) * 10); year = (year & 0x0F) + ((year / 16) * 10); century = (century & 0x0F) + ((century / 16) * 10); } // Convert 12 hour clock to 24 hour clock if necessary if (!(registerB & 0x02) && (hour & 0x80)) { hour = ((hour & 0x7F) + 12) % 24; } // Calculate the full (4-digit) year uint16_t full_year; if(century_register){ full_year = year + century * 100; } else { full_year = year + (CURRENT_YEAR / 100) * 100; if(full_year < CURRENT_YEAR){ full_year += 100; } } return {full_year, month, day, hour, minute, second, 0, 0}; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: listviewfile.cpp // Purpose: Implementation of class 'wxExListViewFile' // Author: Anton van Wezenbeek // Created: 2010-01-29 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/xml/xml.h> #include <wx/extension/configdlg.h> #include <wx/extension/frame.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/dir.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listitem.h> BEGIN_EVENT_TABLE(wxExListViewFile, wxExListViewWithFrame) EVT_IDLE(wxExListViewFile::OnIdle) EVT_MENU(wxID_ADD, wxExListViewFile::OnCommand) EVT_MENU(wxID_CUT, wxExListViewFile::OnCommand) EVT_MENU(wxID_CLEAR, wxExListViewFile::OnCommand) EVT_MENU(wxID_DELETE, wxExListViewFile::OnCommand) EVT_MENU(wxID_PASTE, wxExListViewFile::OnCommand) EVT_LEFT_DOWN(wxExListViewFile::OnMouse) END_EVENT_TABLE() wxExListViewFile::wxExListViewFile(wxWindow* parent, wxExFrameWithHistory* frame, const wxString& file, wxWindowID id, long menu_flags, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxExListViewWithFrame( parent, frame, LIST_FILE, id, menu_flags, NULL, pos, size, style, validator, name) , wxExFile(false) // do not open files in FileLoad and Save , m_AddItemsDialog(NULL) , m_ContentsChanged(false) , m_TextAddFiles(_("Add files")) , m_TextAddFolders(_("Add folders")) , m_TextAddRecursive(_("Recursive")) , m_TextAddWhat(_("Add what")) , m_TextInFolder(_("In folder")) { FileLoad(file); } wxExListViewFile::~wxExListViewFile() { if (m_AddItemsDialog != NULL) { m_AddItemsDialog->Destroy(); } } void wxExListViewFile::AddItems() { int flags = 0; if (wxConfigBase::Get()->ReadBool(m_TextAddFiles, true)) { flags |= wxDIR_FILES; } if (wxConfigBase::Get()->ReadBool(m_TextAddRecursive, false)) { flags |= wxDIR_DIRS; } wxExDirWithListView dir( this, wxExConfigFirstOf(m_TextInFolder), wxExConfigFirstOf(m_TextAddWhat), flags); const auto old_count = GetItemCount(); dir.FindFiles(); const auto new_count = GetItemCount(); if (new_count - old_count > 0) { m_ContentsChanged = true; if (wxConfigBase::Get()->ReadBool("List/SortSync", true)) { SortColumn(_("Modified"), SORT_KEEP); } } #if wxUSE_STATUSBAR const wxString text = _("Added") + wxString::Format(" %d ", new_count - old_count) + _("file(s)"); wxExFrame::StatusText(text); #endif } void wxExListViewFile::AddItemsDialog() { if (m_AddItemsDialog == NULL) { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( m_TextAddWhat, CONFIG_COMBOBOX, wxEmptyString, true)); v.push_back(wxExConfigItem( m_TextInFolder, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); std::set<wxString> set; set.insert(m_TextAddFiles); set.insert(m_TextAddFolders); set.insert(m_TextAddRecursive); v.push_back(wxExConfigItem(set)); m_AddItemsDialog = new wxExConfigDialog(this, v, _("Add Items"), 0, 1, wxOK | wxCANCEL, wxID_ADD); } // Force at least one of the checkboxes to be checked. m_AddItemsDialog->ForceCheckBoxChecked(_("Add")); m_AddItemsDialog->Show(); } void wxExListViewFile::AfterSorting() { // Only if we are not sort syncing set contents changed. if (!wxConfigBase::Get()->ReadBool("List/SortSync", true)) { m_ContentsChanged = true; } } void wxExListViewFile::BuildPopupMenu(wxExMenu& menu) { // This contains the CAN_PASTE flag. long style = wxExMenu::MENU_DEFAULT; if (GetFileName().FileExists() && GetFileName().GetStat().IsReadOnly()) { style |= wxExMenu::MENU_IS_READ_ONLY; } menu.SetStyle(style); wxExListViewWithFrame::BuildPopupMenu(menu); if ((GetSelectedItemCount() == 0) && (!GetFileName().IsOk() || !GetFileName().FileExists() || (GetFileName().FileExists() && !GetFileName().GetStat().IsReadOnly()))) { menu.AppendSeparator(); menu.Append(wxID_ADD); } } void wxExListViewFile::DoFileLoad(bool synced) { EditClearAll(); wxXmlDocument doc; if (!doc.Load(GetFileName().GetFullPath())) { return; } wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { const wxString value = child->GetNodeContent(); if (child->GetName() == "file") { wxExListItem(this, wxFileName(value)).Insert(): } else if (child->GetName() == "folder") { wxExListItem(this, value, child->GetAttribute("extensions")).Insert(); } child = child->GetNext(); } if (synced) { #if wxUSE_STATUSBAR wxExFrame::StatusText( GetFileName(), wxExFrame::STAT_SYNC | wxExFrame::STAT_FULLPATH); #endif } GetFrame()->SetRecentProject(GetFileName().GetFullPath()); } void wxExListViewFile::DoFileNew() { EditClearAll(); } void wxExListViewFile::DoFileSave(bool save_as) { wxXmlNode* root = new wxXmlNode(wxXML_ELEMENT_NODE, "files"); wxXmlNode* comment = new wxXmlNode( wxXML_COMMENT_NODE, wxEmptyString, wxTheApp->GetAppDisplayName() + " project file " + wxDateTime::Now().Format())); root->AddChild(comment); for (auto i = 0; i < GetItemCount(); i++) { const wxString type = GetItemText(item_number, _("Type")); const wxExFileName fn = wxExListItem(this, i).GetFileName(); wxXmlNode* element = new wxXmlNode( wxXML_ELEMENT_NODE, (type.empty() ? "file": "folder")); if (!type.empty()) { element->AddAttribute("extensions", type); } wxXmlNode* text = new wxXmlNode( wxXML_TEXT_NODE, wxEmptyString, fn.GetFullPath()); element->AddChild(text); root->AddChild(element); } wxXmlDocument doc; doc.SetRoot(root); doc.Save(GetFileName().GetFullPath()); } bool wxExListViewFile::ItemFromText(const wxString& text) { if (wxExListViewStandard::ItemFromText(text)) { m_ContentsChanged = true; return true; } else { return false; } } void wxExListViewFile::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { // These are added to disable changing this listview if it is read-only etc. case wxID_CLEAR: case wxID_CUT: case wxID_DELETE: case wxID_PASTE: if (GetFileName().GetStat().IsOk()) { if (!GetFileName().GetStat().IsReadOnly()) { event.Skip(); m_ContentsChanged = true; } } else { event.Skip(); } break; case wxID_ADD: AddItemsDialog(); break; default: wxFAIL; break; } #if wxUSE_STATUSBAR UpdateStatusBar(); #endif } void wxExListViewFile::OnIdle(wxIdleEvent& event) { event.Skip(); if ( IsShown() && GetItemCount() > 0) { CheckSync(); } } void wxExListViewFile::OnMouse(wxMouseEvent& event) { if (event.LeftDown()) { event.Skip(); #if wxUSE_STATUSBAR // If no item has been selected, then show // filename mod time in the statusbar. int flags = wxLIST_HITTEST_ONITEM; const auto index = HitTest(wxPoint(event.GetX(), event.GetY()), flags); if (index < 0) { if (GetFileName().FileExists()) { wxExFrame::StatusText(GetFileName()); } } #endif } else { wxFAIL; } } <commit_msg>simplified code<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: listviewfile.cpp // Purpose: Implementation of class 'wxExListViewFile' // Author: Anton van Wezenbeek // Created: 2010-01-29 // RCS-ID: $Id$ // Copyright: (c) 2010 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/xml/xml.h> #include <wx/extension/configdlg.h> #include <wx/extension/frame.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/dir.h> #include <wx/extension/report/frame.h> #include <wx/extension/report/listitem.h> BEGIN_EVENT_TABLE(wxExListViewFile, wxExListViewWithFrame) EVT_IDLE(wxExListViewFile::OnIdle) EVT_MENU(wxID_ADD, wxExListViewFile::OnCommand) EVT_MENU(wxID_CUT, wxExListViewFile::OnCommand) EVT_MENU(wxID_CLEAR, wxExListViewFile::OnCommand) EVT_MENU(wxID_DELETE, wxExListViewFile::OnCommand) EVT_MENU(wxID_PASTE, wxExListViewFile::OnCommand) EVT_LEFT_DOWN(wxExListViewFile::OnMouse) END_EVENT_TABLE() wxExListViewFile::wxExListViewFile(wxWindow* parent, wxExFrameWithHistory* frame, const wxString& file, wxWindowID id, long menu_flags, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxExListViewWithFrame( parent, frame, LIST_FILE, id, menu_flags, NULL, pos, size, style, validator, name) , wxExFile(false) // do not open files in FileLoad and Save , m_AddItemsDialog(NULL) , m_ContentsChanged(false) , m_TextAddFiles(_("Add files")) , m_TextAddFolders(_("Add folders")) , m_TextAddRecursive(_("Recursive")) , m_TextAddWhat(_("Add what")) , m_TextInFolder(_("In folder")) { FileLoad(file); } wxExListViewFile::~wxExListViewFile() { if (m_AddItemsDialog != NULL) { m_AddItemsDialog->Destroy(); } } void wxExListViewFile::AddItems() { int flags = 0; if (wxConfigBase::Get()->ReadBool(m_TextAddFiles, true)) { flags |= wxDIR_FILES; } if (wxConfigBase::Get()->ReadBool(m_TextAddRecursive, false)) { flags |= wxDIR_DIRS; } wxExDirWithListView dir( this, wxExConfigFirstOf(m_TextInFolder), wxExConfigFirstOf(m_TextAddWhat), flags); const auto old_count = GetItemCount(); dir.FindFiles(); const auto new_count = GetItemCount(); if (new_count - old_count > 0) { m_ContentsChanged = true; if (wxConfigBase::Get()->ReadBool("List/SortSync", true)) { SortColumn(_("Modified"), SORT_KEEP); } } #if wxUSE_STATUSBAR const wxString text = _("Added") + wxString::Format(" %d ", new_count - old_count) + _("file(s)"); wxExFrame::StatusText(text); #endif } void wxExListViewFile::AddItemsDialog() { if (m_AddItemsDialog == NULL) { std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( m_TextAddWhat, CONFIG_COMBOBOX, wxEmptyString, true)); v.push_back(wxExConfigItem( m_TextInFolder, CONFIG_COMBOBOXDIR, wxEmptyString, true, 1000)); std::set<wxString> set; set.insert(m_TextAddFiles); set.insert(m_TextAddFolders); set.insert(m_TextAddRecursive); v.push_back(wxExConfigItem(set)); m_AddItemsDialog = new wxExConfigDialog(this, v, _("Add Items"), 0, 1, wxOK | wxCANCEL, wxID_ADD); } // Force at least one of the checkboxes to be checked. m_AddItemsDialog->ForceCheckBoxChecked(_("Add")); m_AddItemsDialog->Show(); } void wxExListViewFile::AfterSorting() { // Only if we are not sort syncing set contents changed. if (!wxConfigBase::Get()->ReadBool("List/SortSync", true)) { m_ContentsChanged = true; } } void wxExListViewFile::BuildPopupMenu(wxExMenu& menu) { // This contains the CAN_PASTE flag. long style = wxExMenu::MENU_DEFAULT; if (GetFileName().FileExists() && GetFileName().GetStat().IsReadOnly()) { style |= wxExMenu::MENU_IS_READ_ONLY; } menu.SetStyle(style); wxExListViewWithFrame::BuildPopupMenu(menu); if ((GetSelectedItemCount() == 0) && (!GetFileName().IsOk() || !GetFileName().FileExists() || (GetFileName().FileExists() && !GetFileName().GetStat().IsReadOnly()))) { menu.AppendSeparator(); menu.Append(wxID_ADD); } } void wxExListViewFile::DoFileLoad(bool synced) { EditClearAll(); wxXmlDocument doc; if (!doc.Load(GetFileName().GetFullPath())) { return; } wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { const wxString value = child->GetNodeContent(); if (child->GetName() == "file") { wxExListItem(this, value).Insert(): } else if (child->GetName() == "folder") { wxExListItem(this, value, child->GetAttribute("extensions")).Insert(); } child = child->GetNext(); } if (synced) { #if wxUSE_STATUSBAR wxExFrame::StatusText( GetFileName(), wxExFrame::STAT_SYNC | wxExFrame::STAT_FULLPATH); #endif } GetFrame()->SetRecentProject(GetFileName().GetFullPath()); } void wxExListViewFile::DoFileNew() { EditClearAll(); } void wxExListViewFile::DoFileSave(bool save_as) { wxXmlNode* root = new wxXmlNode(wxXML_ELEMENT_NODE, "files"); wxXmlNode* comment = new wxXmlNode( wxXML_COMMENT_NODE, wxEmptyString, wxTheApp->GetAppDisplayName() + " project file " + wxDateTime::Now().Format())); root->AddChild(comment); for (auto i = 0; i < GetItemCount(); i++) { const wxString type = GetItemText(item_number, _("Type")); const wxExFileName fn = wxExListItem(this, i).GetFileName(); wxXmlNode* element = new wxXmlNode( wxXML_ELEMENT_NODE, (type.empty() ? "file": "folder")); if (!type.empty()) { element->AddAttribute("extensions", type); } wxXmlNode* text = new wxXmlNode( wxXML_TEXT_NODE, wxEmptyString, fn.GetFullPath()); element->AddChild(text); root->AddChild(element); } wxXmlDocument doc; doc.SetRoot(root); doc.Save(GetFileName().GetFullPath()); } bool wxExListViewFile::ItemFromText(const wxString& text) { m_ContentsChanged = true; return wxExListViewStandard::ItemFromText(text); } void wxExListViewFile::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { // These are added to disable changing this listview if it is read-only. case wxID_CLEAR: case wxID_CUT: case wxID_DELETE: case wxID_PASTE: if (!GetFileName().GetStat().IsReadOnly()) { event.Skip(); m_ContentsChanged = true; } break; case wxID_ADD: AddItemsDialog(); break; default: wxFAIL; break; } #if wxUSE_STATUSBAR UpdateStatusBar(); #endif } void wxExListViewFile::OnIdle(wxIdleEvent& event) { event.Skip(); if ( IsShown() && GetItemCount() > 0) { CheckSync(); } } void wxExListViewFile::OnMouse(wxMouseEvent& event) { if (event.LeftDown()) { event.Skip(); #if wxUSE_STATUSBAR // If no item has been selected, then show // filename mod time in the statusbar. int flags = wxLIST_HITTEST_ONITEM; const auto index = HitTest(wxPoint(event.GetX(), event.GetY()), flags); if (index < 0) { if (GetFileName().FileExists()) { wxExFrame::StatusText(GetFileName()); } } #endif } else { wxFAIL; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inspagob.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:05:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "inspagob.hxx" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "inspagob.hrc" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdInsertPagesObjsDlg::SdInsertPagesObjsDlg( ::Window* pWindow, const SdDrawDocument* pInDoc, SfxMedium* pSfxMedium, const String& rFileName ) : ModalDialog ( pWindow, SdResId( DLG_INSERT_PAGES_OBJS ) ), aLbTree ( this, SdResId( LB_TREE ) ), aCbxLink ( this, SdResId( CBX_LINK ) ), aCbxMasters ( this, SdResId( CBX_CHECK_MASTERS ) ), aBtnOk ( this, SdResId( BTN_OK ) ), aBtnCancel ( this, SdResId( BTN_CANCEL ) ), aBtnHelp ( this, SdResId( BTN_HELP ) ), pMedium ( pSfxMedium ), mpDoc ( pInDoc ), rName ( rFileName ) { FreeResource(); aLbTree.SetViewFrame( ( (SdDrawDocument*) pInDoc )->GetDocSh()->GetViewShell()->GetViewFrame() ); aLbTree.SetSelectHdl( LINK( this, SdInsertPagesObjsDlg, SelectObjectHdl ) ); // Text wird eingefuegt if( !pMedium ) SetText( String( SdResId( STR_INSERT_TEXT ) ) ); Reset(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdInsertPagesObjsDlg::~SdInsertPagesObjsDlg() { } /************************************************************************* |* |* Fuellt die TreeLB in Abhaengigkeit des Mediums. Ist kein Medium |* vorhanden, handelt es sich um ein Text- und kein Drawdokument |* \************************************************************************/ void SdInsertPagesObjsDlg::Reset() { if( pMedium ) { aLbTree.SetSelectionMode( MULTIPLE_SELECTION ); // transfer ownership of Medium aLbTree.Fill( mpDoc, pMedium, rName ); } else { Color aColor( COL_WHITE ); Bitmap aBmpText( SdResId( BMP_DOC_TEXT ) ); Image aImgText( aBmpText, aColor ); Bitmap aBmpTextH( SdResId( BMP_DOC_TEXT_H ) ); Image aImgTextH( aBmpTextH, Color( COL_BLACK ) ); SvLBoxEntry* pEntry = aLbTree.InsertEntry( rName, aImgText, aImgText ); aLbTree.SetExpandedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); aLbTree.SetCollapsedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); } aCbxMasters.Check( TRUE ); } /************************************************************************* |* |* Liefert die Liste zurueck |* nType == 0 -> Seiten |* nType == 1 -> Objekte |* \************************************************************************/ List* SdInsertPagesObjsDlg::GetList( USHORT nType ) { // Bei Draw-Dokumenten muss bei der Selektion des Dokumentes NULL // zurueckgegeben werden if( pMedium ) { // Um zu gewaehrleisten, dass die Bookmarks geoeffnet sind // (Wenn gesamtes Dokument ausgewaehlt wurde) aLbTree.GetBookmarkDoc(); // Wenn das Dokument (mit-)selektiert oder nichst selektiert ist, // wird das gesamte Dokument (und nicht mehr!) eingefuegt. if( aLbTree.GetSelectionCount() == 0 || ( aLbTree.IsSelected( aLbTree.First() ) ) ) //return( aLbTree.GetBookmarkList( nType ) ); return( NULL ); // #37350# } return( aLbTree.GetSelectEntryList( nType ) ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsLink() { return( aCbxLink.IsChecked() ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsRemoveUnnessesaryMasterPages() const { return( aCbxMasters.IsChecked() ); } /************************************************************************* |* |* Enabled und selektiert Endfarben-LB |* \************************************************************************/ IMPL_LINK( SdInsertPagesObjsDlg, SelectObjectHdl, void *, EMPTYARG ) { if( aLbTree.IsLinkableSelected() ) aCbxLink.Enable(); else aCbxLink.Disable(); return( 0 ); } <commit_msg>INTEGRATION: CWS changefileheader (1.10.298); FILE MERGED 2008/04/01 12:38:42 thb 1.10.298.2: #i85898# Stripping all external header guards 2008/03/31 13:57:46 rt 1.10.298.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inspagob.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #include "inspagob.hxx" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #include "ViewShell.hxx" #include "inspagob.hrc" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdInsertPagesObjsDlg::SdInsertPagesObjsDlg( ::Window* pWindow, const SdDrawDocument* pInDoc, SfxMedium* pSfxMedium, const String& rFileName ) : ModalDialog ( pWindow, SdResId( DLG_INSERT_PAGES_OBJS ) ), aLbTree ( this, SdResId( LB_TREE ) ), aCbxLink ( this, SdResId( CBX_LINK ) ), aCbxMasters ( this, SdResId( CBX_CHECK_MASTERS ) ), aBtnOk ( this, SdResId( BTN_OK ) ), aBtnCancel ( this, SdResId( BTN_CANCEL ) ), aBtnHelp ( this, SdResId( BTN_HELP ) ), pMedium ( pSfxMedium ), mpDoc ( pInDoc ), rName ( rFileName ) { FreeResource(); aLbTree.SetViewFrame( ( (SdDrawDocument*) pInDoc )->GetDocSh()->GetViewShell()->GetViewFrame() ); aLbTree.SetSelectHdl( LINK( this, SdInsertPagesObjsDlg, SelectObjectHdl ) ); // Text wird eingefuegt if( !pMedium ) SetText( String( SdResId( STR_INSERT_TEXT ) ) ); Reset(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdInsertPagesObjsDlg::~SdInsertPagesObjsDlg() { } /************************************************************************* |* |* Fuellt die TreeLB in Abhaengigkeit des Mediums. Ist kein Medium |* vorhanden, handelt es sich um ein Text- und kein Drawdokument |* \************************************************************************/ void SdInsertPagesObjsDlg::Reset() { if( pMedium ) { aLbTree.SetSelectionMode( MULTIPLE_SELECTION ); // transfer ownership of Medium aLbTree.Fill( mpDoc, pMedium, rName ); } else { Color aColor( COL_WHITE ); Bitmap aBmpText( SdResId( BMP_DOC_TEXT ) ); Image aImgText( aBmpText, aColor ); Bitmap aBmpTextH( SdResId( BMP_DOC_TEXT_H ) ); Image aImgTextH( aBmpTextH, Color( COL_BLACK ) ); SvLBoxEntry* pEntry = aLbTree.InsertEntry( rName, aImgText, aImgText ); aLbTree.SetExpandedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); aLbTree.SetCollapsedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); } aCbxMasters.Check( TRUE ); } /************************************************************************* |* |* Liefert die Liste zurueck |* nType == 0 -> Seiten |* nType == 1 -> Objekte |* \************************************************************************/ List* SdInsertPagesObjsDlg::GetList( USHORT nType ) { // Bei Draw-Dokumenten muss bei der Selektion des Dokumentes NULL // zurueckgegeben werden if( pMedium ) { // Um zu gewaehrleisten, dass die Bookmarks geoeffnet sind // (Wenn gesamtes Dokument ausgewaehlt wurde) aLbTree.GetBookmarkDoc(); // Wenn das Dokument (mit-)selektiert oder nichst selektiert ist, // wird das gesamte Dokument (und nicht mehr!) eingefuegt. if( aLbTree.GetSelectionCount() == 0 || ( aLbTree.IsSelected( aLbTree.First() ) ) ) //return( aLbTree.GetBookmarkList( nType ) ); return( NULL ); // #37350# } return( aLbTree.GetSelectEntryList( nType ) ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsLink() { return( aCbxLink.IsChecked() ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsRemoveUnnessesaryMasterPages() const { return( aCbxMasters.IsChecked() ); } /************************************************************************* |* |* Enabled und selektiert Endfarben-LB |* \************************************************************************/ IMPL_LINK( SdInsertPagesObjsDlg, SelectObjectHdl, void *, EMPTYARG ) { if( aLbTree.IsLinkableSelected() ) aCbxLink.Enable(); else aCbxLink.Disable(); return( 0 ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: assclass.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:22:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INC_ASSCLASS #define INC_ASSCLASS #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif #define MAX_PAGES 10 class List; class Control; class SD_DLLPUBLIC Assistent { List* pPages[MAX_PAGES]; //enthaelt fuer jede Seite die Controls die //korrekt geschaltet werden muessen UINT8 nPages; //gibt die Anzahl der Seiten an UINT8 nCurrentPage; //gibt die aktuelle Seite an BOOL* pPageStatus; public: Assistent(UINT8 nNoOfPage); BOOL IsEnabled( UINT8 nPage ); void EnablePage( UINT8 nPage ); void DisablePage( UINT8 nPage ); BOOL InsertControl(UINT8 nDestPage,Control* pUsedControl); //fuegt einer spezifizierten Seite ein Control hinzu BOOL NextPage(); //springt zur naechsten Seite BOOL PreviousPage(); //springt zur vorherigen Seite BOOL GotoPage(const UINT8 nPageToGo); //springt zu einer angegebenen Seite BOOL IsLastPage(); //gibt an ob die aktuelle Seite die letzte ist BOOL IsFirstPage(); //gibt an ob die aktuelle Seite die erste ist UINT8 GetCurrentPage(); //gibt die aktuelle Seite zurueck ~Assistent(); }; #endif <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006/11/22 12:42:03 cl 1.3.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: assclass.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:40:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INC_ASSCLASS #define INC_ASSCLASS #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif #define MAX_PAGES 10 class List; class Control; class SD_DLLPUBLIC Assistent { List* mpPages[MAX_PAGES]; //enthaelt fuer jede Seite die Controls die //korrekt geschaltet werden muessen int mnPages; //gibt die Anzahl der Seiten an int mnCurrentPage; //gibt die aktuelle Seite an bool* mpPageStatus; public: Assistent(int nNoOfPage); bool IsEnabled( int nPage ); void EnablePage( int nPage ); void DisablePage( int nPage ); bool InsertControl(int nDestPage,Control* pUsedControl); //fuegt einer spezifizierten Seite ein Control hinzu bool NextPage(); //springt zur naechsten Seite bool PreviousPage(); //springt zur vorherigen Seite bool GotoPage(const int nPageToGo); //springt zu einer angegebenen Seite bool IsLastPage(); //gibt an ob die aktuelle Seite die letzte ist bool IsFirstPage(); //gibt an ob die aktuelle Seite die erste ist int GetCurrentPage(); //gibt die aktuelle Seite zurueck ~Assistent(); }; #endif <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014-2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : app/oglplus/main.cpp */ /* project : */ /* description: liberated from oglplus example '007_glm_boxes.cpp' */ /* */ /**************************************************************************************************/ // includes, system #include <GL/glew.h> // ::glew* #include <boost/filesystem.hpp> // boost::filesystem::path #include <oglplus/all.hpp> #include <oglplus/opt/resources.hpp> #include <oglplus/shapes/cube.hpp> #include <csignal> // SIG* #include <glm/glm.hpp> #include <oglplus/interop/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/io.hpp> // includes, project #include <platform/glut/application/base.hpp> #include <platform/glut/window/simple.hpp> #include <platform/oglplus/application.hpp> #include <support/signal_handler.hpp> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) class window : public platform::glut::window::simple { using inherited = platform::glut::window::simple; using rect = platform::window::rect; public: explicit window(std::string const& a, rect const& b, std::string const& c) : inherited (a, b), ctx_ (), prg_ (), make_cube_ (), cube_instr_ (make_cube_.Instructions()), cube_indices_ (make_cube_.Indices()), frame_time_ (prg_, "Time") { TRACE("<unnamed>::window::window"); using namespace oglplus; { namespace bfs = boost::filesystem; bfs::path const p(c); std::string const d(p.parent_path().string()); std::string const f(p.stem().string()); #if defined(_WIN32) static std::string const btrack("../.."); #else static std::string const btrack(".."); #endif ResourceFile vs_src(d + "/" + btrack + "/share/shader/glsl", f, ".vs.glsl"); ResourceFile fs_src(d + "/" + btrack + "/share/shader/glsl", f, ".fs.glsl"); prg_ << VertexShader().Source(GLSLSource::FromStream(vs_src.stream())) << FragmentShader().Source(GLSLSource::FromStream(fs_src.stream())); prg_.Link().Use(); } cube_va_.Bind(); positions_.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint size(make_cube_.Positions(data)); Buffer::Data(Buffer::Target::Array, data); VertexArrayAttrib attr(prg_, "Position"); attr.Setup<GLfloat>(size); attr.Enable(); } normals_.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint size(make_cube_.Normals(data)); Buffer::Data(Buffer::Target::Array, data); VertexArrayAttrib attr(prg_, "Normal"); attr.Setup<GLfloat>(size); attr.Enable(); } { ShaderStorageBlock block(prg_, "DiffuseListBuf"); block.Binding(0); lights_.Bind(Buffer::Target::ShaderStorage); using diffuse_list_type = std::array<glm::vec3 const, 2>; diffuse_list_type const data = { glm::vec3(0.90, 0.90, 0.10), glm::vec3(0.75, 0.75, 0.75), }; Buffer::Data(Buffer::Target::ShaderStorage, data, BufferUsage::DynamicDraw); lights_.BindBaseShaderStorage(0); } ctx_.ClearColor(0.95f, 0.95f, 0.95f, 0.0f); ctx_.ClearDepth(1.0f); ctx_.Enable(Capability::DepthTest); Typechecked<Uniform<glm::vec3>> (prg_, "LightPos"). Set(glm::vec3(7.0, 3.0, -1.0)); Typechecked<Uniform<glm::mat4x4>>(prg_, "ScaleMatrix"). Set(glm::scale(glm::mat4(1.0), glm::vec3(1.0, 0.3, 1.7))); } virtual ~window() { TRACE("<unnamed>::window::~window"); } private: virtual void frame_render_one() { TRACE_NEVER("<unnamed>::window::frame_render_one"); ctx_.Clear().ColorBuffer().DepthBuffer(); { using namespace std::chrono; frame_time_. Set(duration_cast<duration<double>>(support::clock::now().time_since_epoch()).count()); } cube_instr_.Draw(cube_indices_, 36); } virtual void reshape(glm::ivec2 const& size) { TRACE("<unnamed>::window::reshape"); ctx_.Viewport(size.x, size.y); auto camera(glm::perspective(53.0f*3.1415f/180.f, float(size.x)/float(size.y), 1.0f, 100.0f) * glm::lookAt(glm::vec3(21.0f, 8.0f, 7.0f), glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, 1.0f, 0.0f))); oglplus::Uniform<glm::mat4x4>(prg_, "CameraMatrix").Set(camera); } oglplus::Context ctx_; oglplus::Program prg_; oglplus::shapes::Cube make_cube_; oglplus::shapes::DrawingInstructions cube_instr_; oglplus::shapes::Cube::IndexArray cube_indices_; oglplus::VertexArray cube_va_; oglplus::Buffer positions_; oglplus::Buffer normals_; oglplus::Buffer lights_; oglplus::Lazy<oglplus::Uniform<float>> frame_time_; }; class application : public platform::glut::application::base { using command_line = platform::application::command_line; using inherited = platform::glut::application::base; using rect = platform::window::rect; public: static void terminate(signed signo) { TRACE("<unnamed>::application::terminate"); inherited::terminate = true; std::cout << '\n' << "terminating by user request ('" << support::signal_name(signo) << "' " << signo << ")" << '\n'; } explicit application(command_line const& a) : inherited(a), window_ (nullptr) { TRACE("<unnamed>::application::application"); } virtual ~application() { TRACE("<unnamed>::application::~application"); } virtual void process_command_line() { TRACE("<unnamed>::application::process_command_line"); inherited::process_command_line(); window_.reset(new window(command_line_.argv0, rect(50, 50, 1440, 900), command_line_.argv0)); } private: std::unique_ptr<window> window_; }; // variables, internal // functions, internal } // namespace { int main(int argc, char const* argv[]) { TRACE("main"); support::signal_handler::instance->handler(SIGINT, &application::terminate); support::signal_handler::instance->handler(SIGTERM, &application::terminate); namespace pa = platform::application; namespace poa = platform::oglplus::application; return poa::execute<application>(pa::command_line(argc, argv), std::nothrow); } <commit_msg>whitespace<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014-2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : app/oglplus/main.cpp */ /* project : */ /* description: liberated from oglplus example '007_glm_boxes.cpp' */ /* */ /**************************************************************************************************/ // includes, system #include <GL/glew.h> // ::glew* #include <boost/filesystem.hpp> // boost::filesystem::path #include <oglplus/all.hpp> #include <oglplus/opt/resources.hpp> #include <oglplus/shapes/cube.hpp> #include <csignal> // SIG* #include <glm/glm.hpp> #include <oglplus/interop/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/io.hpp> // includes, project #include <platform/glut/application/base.hpp> #include <platform/glut/window/simple.hpp> #include <platform/oglplus/application.hpp> #include <support/signal_handler.hpp> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) class window : public platform::glut::window::simple { using inherited = platform::glut::window::simple; using rect = platform::window::rect; public: explicit window(std::string const& a, rect const& b, std::string const& c) : inherited (a, b), ctx_ (), prg_ (), make_cube_ (), cube_instr_ (make_cube_.Instructions()), cube_indices_ (make_cube_.Indices()), frame_time_ (prg_, "Time") { TRACE("<unnamed>::window::window"); using namespace oglplus; { namespace bfs = boost::filesystem; bfs::path const p(c); std::string const d(p.parent_path().string()); std::string const f(p.stem().string()); #if defined(_WIN32) static std::string const btrack("../.."); #else static std::string const btrack(".."); #endif ResourceFile vs_src(d + "/" + btrack + "/share/shader/glsl", f, ".vs.glsl"); ResourceFile fs_src(d + "/" + btrack + "/share/shader/glsl", f, ".fs.glsl"); prg_ << VertexShader().Source(GLSLSource::FromStream(vs_src.stream())) << FragmentShader().Source(GLSLSource::FromStream(fs_src.stream())); prg_.Link().Use(); } cube_va_.Bind(); positions_.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint size(make_cube_.Positions(data)); Buffer::Data(Buffer::Target::Array, data); VertexArrayAttrib attr(prg_, "Position"); attr.Setup<GLfloat>(size); attr.Enable(); } normals_.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint size(make_cube_.Normals(data)); Buffer::Data(Buffer::Target::Array, data); VertexArrayAttrib attr(prg_, "Normal"); attr.Setup<GLfloat>(size); attr.Enable(); } { ShaderStorageBlock block(prg_, "DiffuseListBuf"); block.Binding(0); lights_.Bind(Buffer::Target::ShaderStorage); using diffuse_list_type = std::array<glm::vec3 const, 2>; diffuse_list_type const data = { glm::vec3(0.90, 0.90, 0.10), glm::vec3(0.75, 0.75, 0.75), }; Buffer::Data(Buffer::Target::ShaderStorage, data, BufferUsage::DynamicDraw); lights_.BindBaseShaderStorage(0); } ctx_.ClearColor(0.95f, 0.95f, 0.95f, 0.0f); ctx_.ClearDepth(1.0f); ctx_.Enable(Capability::DepthTest); Typechecked<Uniform<glm::vec3>> (prg_, "LightPos"). Set(glm::vec3(7.0, 3.0, -1.0)); Typechecked<Uniform<glm::mat4x4>>(prg_, "ScaleMatrix"). Set(glm::scale(glm::mat4(1.0), glm::vec3(1.0, 0.3, 1.7))); } virtual ~window() { TRACE("<unnamed>::window::~window"); } private: virtual void frame_render_one() { TRACE_NEVER("<unnamed>::window::frame_render_one"); ctx_.Clear().ColorBuffer().DepthBuffer(); { using namespace std::chrono; frame_time_. Set(duration_cast<duration<double>>(support::clock::now().time_since_epoch()).count()); } cube_instr_.Draw(cube_indices_, 36); } virtual void reshape(glm::ivec2 const& size) { TRACE("<unnamed>::window::reshape"); ctx_.Viewport(size.x, size.y); auto camera(glm::perspective(53.0f*3.1415f/180.f, float(size.x)/float(size.y), 1.0f, 100.0f) * glm::lookAt(glm::vec3(21.0f, 8.0f, 7.0f), glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 0.0f, 1.0f, 0.0f))); oglplus::Uniform<glm::mat4x4>(prg_, "CameraMatrix").Set(camera); } oglplus::Context ctx_; oglplus::Program prg_; oglplus::shapes::Cube make_cube_; oglplus::shapes::DrawingInstructions cube_instr_; oglplus::shapes::Cube::IndexArray cube_indices_; oglplus::VertexArray cube_va_; oglplus::Buffer positions_; oglplus::Buffer normals_; oglplus::Buffer lights_; oglplus::Lazy<oglplus::Uniform<float>> frame_time_; }; class application : public platform::glut::application::base { using command_line = platform::application::command_line; using inherited = platform::glut::application::base; using rect = platform::window::rect; public: static void terminate(signed signo) { TRACE("<unnamed>::application::terminate"); inherited::terminate = true; std::cout << '\n' << "terminating by user request ('" << support::signal_name(signo) << "' " << signo << ")" << '\n'; } explicit application(command_line const& a) : inherited(a), window_ (nullptr) { TRACE("<unnamed>::application::application"); } virtual ~application() { TRACE("<unnamed>::application::~application"); } virtual void process_command_line() { TRACE("<unnamed>::application::process_command_line"); inherited::process_command_line(); window_.reset(new window(command_line_.argv0, rect(50, 50, 1440, 900), command_line_.argv0)); } private: std::unique_ptr<window> window_; }; // variables, internal // functions, internal } // namespace { int main(int argc, char const* argv[]) { TRACE("main"); support::signal_handler::instance->handler(SIGINT, &application::terminate); support::signal_handler::instance->handler(SIGTERM, &application::terminate); namespace pa = platform::application; namespace poa = platform::oglplus::application; return poa::execute<application>(pa::command_line(argc, argv), std::nothrow); } <|endoftext|>
<commit_before>/** * @file State.cpp * * @brief Implementation file for State class. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include "State.h" #include <cmath> /** * Creates a state object initialised with starting values of angle of robot * based on encoder value, velocity of robot (both typically should be zero) * and the initial default 'action state' to perform. */ State::State(double _theta, double _theta_dot, ROBOT_STATE _robot_state) : theta(_theta), theta_dot(_theta_dot), robot_state(_robot_state) { } /** * Computes the reward value of a given state through the principle of energy * increase requirements for the system; the equation used is, * * \f[ R = g \cos(\theta) + \frac{1}{2} \dot\theta ^2 \f] * * where R is the reward, \f$\theta\f$ is the angle and \f$\dot\theta\f$ is the velocity. * This equation simply sums the kinetic and potential energies for the state. * */ double State::getReward() { //return kinetic + potential return g * std::cos(theta) + 0.5 * theta_dot * theta_dot; } /** * Computes the reward value of a given state through the principle of height * maximisation. The equation used in this case is, * * \f[ R = \frac{\theta \dot\theta}{|\dot\theta|} + 4 \f] * * where R is the reward, \f$ \theta \f$ the angle and \f$\dot\theta\f$ is the velocity. * This equation gets the height of a state and the sign of the velocity (to determine * direction of swinging) with an offset of 4 included to ensure the return value is * always positive. * */ double State::getHeightReward() { //return height and sign of velocity, add 4 so it is always positive return (theta * theta_dot) / std::abs(theta_dot) + 4; }<commit_msg>updated documentation<commit_after>/** * @file State.cpp * * @brief Implementation file for State struct. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ #include "State.h" #include <cmath> /** * Creates a state object initialised with starting values of angle of robot * based on encoder value, velocity of robot (both typically should be zero) * and the initial default 'action state' to perform. */ State::State(double _theta, double _theta_dot, ROBOT_STATE _robot_state) : theta(_theta), theta_dot(_theta_dot), robot_state(_robot_state) { } /** * Computes the reward value of a given state through the principle of energy * increase requirements for the system; the equation used is, * * \f[ R = g \cos(\theta) + \frac{1}{2} \dot\theta ^2 \f] * * where R is the reward, \f$\theta\f$ is the angle and \f$\dot\theta\f$ is the velocity. * This equation simply sums the kinetic and potential energies for the state. * */ double State::getReward() { //return kinetic + potential return g * std::cos(theta) + 0.5 * theta_dot * theta_dot; } /** * Computes the reward value of a given state through the principle of height * maximisation. The equation used in this case is, * * \f[ R = \frac{\theta \dot\theta}{|\dot\theta|} + 4 \f] * * where R is the reward, \f$ \theta \f$ the angle and \f$\dot\theta\f$ is the velocity. * This equation gets the height of a state and the sign of the velocity (to determine * direction of swinging) with an offset of 4 included to ensure the return value is * always positive. * */ double State::getHeightReward() { //return height and sign of velocity, add 4 so it is always positive return (theta * theta_dot) / std::abs(theta_dot) + 4; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <asp/Core/AffineEpipolar.h> #include <asp/Core/OpenCVUtils.h> #include <asp/Core/StereoSettings.h> #include <vw/Math/Vector.h> #include <vw/Math/Matrix.h> #include <vw/Math/RANSAC.h> #include <vw/Math/LinearAlgebra.h> #include <vw/InterestPoint/InterestData.h> #include <vw/Core/Stopwatch.h> #include <opencv2/calib3d.hpp> #include <vector> using namespace vw; using namespace vw::math; namespace asp { // Solves for Affine Fundamental Matrix as per instructions in // Multiple View Geometry. Outlier elimination happens later. Matrix<double> linear_affine_fundamental_matrix(std::vector<ip::InterestPoint> const& ip1, std::vector<ip::InterestPoint> const& ip2) { // (i) Compute the centroid of X and delta X Matrix<double> delta_x(ip1.size(), 4); Vector4 mean_x; for (size_t i = 0; i < ip1.size(); i++) { delta_x(i, 0) = ip2[i].x; delta_x(i, 1) = ip2[i].y; delta_x(i, 2) = ip1[i].x; delta_x(i, 3) = ip1[i].y; mean_x += select_row(delta_x, i) / double(ip1.size()); } for (size_t i = 0; i < ip1.size(); i++) select_row(delta_x,i) -= mean_x; Matrix<double> U, VT; Vector<double> S; svd(transpose(delta_x), U, S, VT); Vector<double> N = select_col(U, 3); double e = -transpose(N) * mean_x; Matrix<double> f(3,3); f(0,2) = N(0); f(1,2) = N(1); f(2,2) = e; f(2,0) = N(2); f(2,1) = N(3); return f; } void solve_y_scaling(std::vector<ip::InterestPoint> const & ip1, std::vector<ip::InterestPoint> const & ip2, Matrix<double> & affine_left, Matrix<double> & affine_right) { Matrix<double> a(ip1.size(), 2); Vector<double> b(ip1.size()); for (size_t i = 0; i < ip1.size(); i++) { select_row(a, i) = subvector(affine_right*Vector3(ip2[i].x, ip2[i].y, 1), 1, 2); b[i] = (affine_left*Vector3(ip1[i].x, ip1[i].y, 1))(1); } Vector<double> scaling = least_squares(a, b); submatrix(affine_right,0,0,2,2) *= scaling[0]; affine_right(1,2) = scaling[1]; } void solve_x_shear(std::vector<ip::InterestPoint> const & ip1, std::vector<ip::InterestPoint> const & ip2, Matrix<double> & affine_left, Matrix<double> & affine_right) { Matrix<double> a(ip1.size(), 3); Vector<double> b(ip1.size()); for (size_t i = 0; i < ip1.size(); i++) { select_row(a, i) = affine_right * Vector3(ip2[i].x, ip2[i].y, 1); b[i] = (affine_left * Vector3(ip1[i].x, ip1[i].y, 1))(0); } Vector<double> shear = least_squares(a, b); Matrix<double> interm = math::identity_matrix<3>(); interm(0, 1) = -shear[1] / 2.0; affine_left = interm * affine_left; interm = math::identity_matrix<3>(); interm(0, 0) = shear[0]; interm(0, 1) = shear[1] / 2.0; interm(0, 2) = shear[2]; affine_right = interm * affine_right; } // A functor which returns the best fit left and right 3x3 matrices // for epipolar alignment. Store them as a single 3x7 matrix. The // last column will have the upper-right corner of the intersections // of the domains of the left and right images with the resulting // transformed applied to them. struct BestFitEpipolarAlignment { Vector2i m_ldims, m_rdims; BestFitEpipolarAlignment(Vector2i const& left_image_dims, Vector2i const& right_image_dims): m_ldims(left_image_dims), m_rdims(right_image_dims) {} typedef vw::Matrix<double, 3, 7> result_type; /// The fundamental matrix needs 8 points. // TODO(oalexan1): Should a bigger minimum be used for robustness? template <class InterestPointT> size_t min_elements_needed_for_fit(InterestPointT const& /*example*/) const { return 8; } /// This function can match points in any container that supports /// the size() and operator[] methods. The container is usually a /// vw::Vector<>, but you could substitute other classes here as /// well. template <class InterestPointT> vw::Matrix<double> operator()(std::vector<InterestPointT> const& ip1, std::vector<InterestPointT> const& ip2, vw::Matrix<double> const& /*seed_input*/ = vw::Matrix<double>() ) const { // check consistency VW_ASSERT( ip1.size() == ip2.size(), vw::ArgumentErr() << "Cannot compute fundamental matrix. " << "ip1 and ip2 are not the same size." ); VW_ASSERT( !ip1.empty() && ip1.size() >= min_elements_needed_for_fit(ip1[0]), vw::ArgumentErr() << "Cannot compute fundamental matrix. " << "Need at at least 8 points, but got: " << ip1.size() << ".\n"); // Compute the affine fundamental matrix Matrix<double> fund = linear_affine_fundamental_matrix(ip1, ip2); // Solve for rotation matrices double Hl = sqrt(fund(2, 0)*fund(2, 0) + fund(2, 1)*fund(2, 1)); double Hr = sqrt(fund(0, 2)*fund(0, 2) + fund(1, 2)*fund(1, 2)); Vector2 epipole(-fund(2, 1), fund(2, 0)), epipole_prime(-fund(1, 2), fund(0, 2)); if (epipole.x() < 0) epipole = -epipole; if (epipole_prime.x() < 0) epipole_prime = -epipole_prime; epipole.y() = -epipole.y(); epipole_prime.y() = -epipole_prime.y(); Matrix<double> left_matrix = math::identity_matrix<3>(); Matrix<double> right_matrix = math::identity_matrix<3>(); left_matrix(0, 0) = epipole[0]/Hl; left_matrix(0, 1) = -epipole[1]/Hl; left_matrix(1, 0) = epipole[1]/Hl; left_matrix(1, 1) = epipole[0]/Hl; right_matrix(0, 0) = epipole_prime[0]/Hr; right_matrix(0, 1) = -epipole_prime[1]/Hr; right_matrix(1, 0) = epipole_prime[1]/Hr; right_matrix(1, 1) = epipole_prime[0]/Hr; // Solve for ideal scaling and translation solve_y_scaling(ip1, ip2, left_matrix, right_matrix); // Solve for ideal shear, scale, and translation of X axis solve_x_shear(ip1, ip2, left_matrix, right_matrix); // Work out the ideal render size BBox2i output_bbox, right_bbox; output_bbox.grow(subvector(left_matrix * Vector3(0, 0, 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(m_ldims.x(), 0, 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(m_ldims.x(), m_ldims.y(), 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(0, m_ldims.y(), 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(0, 0, 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(m_rdims.x(), 0, 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(m_rdims.x(), m_rdims.y(), 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(0, m_rdims.y(), 1), 0, 2)); output_bbox.crop(right_bbox); left_matrix (0, 2) -= output_bbox.min().x(); right_matrix(0, 2) -= output_bbox.min().x(); left_matrix (1, 2) -= output_bbox.min().y(); right_matrix(1, 2) -= output_bbox.min().y(); // Concatenate these into the answer result_type T; submatrix(T, 0, 0, 3, 3) = left_matrix; submatrix(T, 0, 3, 3, 3) = right_matrix; // Also save the domain after alignment T(0, 6) = output_bbox.width(); T(1, 6) = output_bbox.height(); return T; } }; // Find the absolute difference of the y components of the given // interest point pair after applying to those points the given // epipolar alignment matrices. If these matrices are correct, // and the interest point pair is not an outlier, this // absolute difference should be close to 0. struct EpipolarAlignmentError { template <class TransformT, class InterestPointT> double operator() (TransformT const& T, InterestPointT const& ip1, InterestPointT const& ip2) const { Matrix<double> left_matrix = submatrix(T, 0, 0, 3, 3); Matrix<double> right_matrix = submatrix(T, 0, 3, 3, 3); Vector3 L = left_matrix * Vector3(ip1.x, ip1.y, 1); Vector3 R = right_matrix * Vector3(ip2.x, ip2.y, 1); double diff = L[1] - R[1]; return std::abs(diff); } }; // Helper function to instantiate a RANSAC class object and immediately call it template <class ContainerT1, class ContainerT2, class FittingFuncT, class ErrorFuncT> typename FittingFuncT::result_type ransac(std::vector<ContainerT1> const& p1, std::vector<ContainerT2> const& p2, FittingFuncT const& fitting_func, ErrorFuncT const& error_func, int num_iterations, double inlier_threshold, int min_num_output_inliers, bool reduce_min_num_output_inliers_if_no_fit = false ) { RandomSampleConsensus<FittingFuncT, ErrorFuncT> ransac_instance(fitting_func, error_func, num_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit ); return ransac_instance(p1,p2); } // Main function that other parts of ASP should use Vector2i affine_epipolar_rectification(Vector2i const& left_image_dims, Vector2i const& right_image_dims, double inlier_threshold, int num_ransac_iterations, std::vector<ip::InterestPoint> const& ip1, std::vector<ip::InterestPoint> const& ip2, Matrix<double>& left_matrix, Matrix<double>& right_matrix, // optionally return the inliers std::vector<size_t> * inliers_ptr) { int min_num_output_inliers = ip1.size() / 2; bool reduce_min_num_output_inliers_if_no_fit = true; vw::Matrix<double> T; Stopwatch sw; sw.start(); vw_out() << "Computing the epipolar rectification matrices " << "using RANSAC with " << num_ransac_iterations << " iterations and inlier threshold " << inlier_threshold << ".\n"; // If RANSAC fails, it will throw an exception BestFitEpipolarAlignment func(left_image_dims, right_image_dims); EpipolarAlignmentError error_metric; std::vector<size_t> inlier_indices; RandomSampleConsensus<BestFitEpipolarAlignment, EpipolarAlignmentError> ransac(func, error_metric, num_ransac_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit); T = ransac(ip1, ip2); inlier_indices = ransac.inlier_indices(T, ip1, ip2); vw_out() << "Found " << inlier_indices.size() << " / " << ip1.size() << " inliers.\n"; sw.stop(); vw_out(DebugMessage,"asp") << "Elapsed time in computing rectification matrices: " << sw.elapsed_seconds() << " seconds.\n"; // Extract the matrices and the cropped transformed box from the computed transform left_matrix = submatrix(T, 0, 0, 3, 3); right_matrix = submatrix(T, 0, 3, 3, 3); Vector2i trans_crop_box(T(0, 6), T(1, 6)); // Find the maximum error for inliers double max_err = 0.0; for (size_t it = 0; it < inlier_indices.size(); it++) { int i = inlier_indices[it]; max_err = std::max(max_err, error_metric(T, ip1[i], ip2[i])); } vw_out() << "The maximum absolute difference of the y components of the " << "inlier interest points with the alignment matrices applied to them: " << max_err << " pixels." << std::endl; // Optionally return the inliers if (inliers_ptr != NULL) *inliers_ptr = inlier_indices; return trans_crop_box; } } // end namespace asp <commit_msg>Bugfix: additional outlier filtering (by range) added, on top of using the affine epopolar metric<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <asp/Core/AffineEpipolar.h> #include <asp/Core/OpenCVUtils.h> #include <asp/Core/StereoSettings.h> #include <vw/Math/Vector.h> #include <vw/Math/Matrix.h> #include <vw/Math/RANSAC.h> #include <vw/Math/LinearAlgebra.h> #include <vw/InterestPoint/InterestData.h> #include <vw/Core/Stopwatch.h> #include <opencv2/calib3d.hpp> #include <vector> using namespace vw; using namespace vw::math; namespace asp { // Solves for Affine Fundamental Matrix as per instructions in // Multiple View Geometry. Outlier elimination happens later. Matrix<double> linear_affine_fundamental_matrix(std::vector<ip::InterestPoint> const& ip1, std::vector<ip::InterestPoint> const& ip2) { // (i) Compute the centroid of X and delta X Matrix<double> delta_x(ip1.size(), 4); Vector4 mean_x; for (size_t i = 0; i < ip1.size(); i++) { delta_x(i, 0) = ip2[i].x; delta_x(i, 1) = ip2[i].y; delta_x(i, 2) = ip1[i].x; delta_x(i, 3) = ip1[i].y; mean_x += select_row(delta_x, i) / double(ip1.size()); } for (size_t i = 0; i < ip1.size(); i++) select_row(delta_x,i) -= mean_x; Matrix<double> U, VT; Vector<double> S; svd(transpose(delta_x), U, S, VT); Vector<double> N = select_col(U, 3); double e = -transpose(N) * mean_x; Matrix<double> f(3,3); f(0,2) = N(0); f(1,2) = N(1); f(2,2) = e; f(2,0) = N(2); f(2,1) = N(3); return f; } void solve_y_scaling(std::vector<ip::InterestPoint> const & ip1, std::vector<ip::InterestPoint> const & ip2, Matrix<double> & affine_left, Matrix<double> & affine_right) { Matrix<double> a(ip1.size(), 2); Vector<double> b(ip1.size()); for (size_t i = 0; i < ip1.size(); i++) { select_row(a, i) = subvector(affine_right*Vector3(ip2[i].x, ip2[i].y, 1), 1, 2); b[i] = (affine_left*Vector3(ip1[i].x, ip1[i].y, 1))(1); } Vector<double> scaling = least_squares(a, b); submatrix(affine_right,0,0,2,2) *= scaling[0]; affine_right(1,2) = scaling[1]; } void solve_x_shear(std::vector<ip::InterestPoint> const & ip1, std::vector<ip::InterestPoint> const & ip2, Matrix<double> & affine_left, Matrix<double> & affine_right) { Matrix<double> a(ip1.size(), 3); Vector<double> b(ip1.size()); for (size_t i = 0; i < ip1.size(); i++) { select_row(a, i) = affine_right * Vector3(ip2[i].x, ip2[i].y, 1); b[i] = (affine_left * Vector3(ip1[i].x, ip1[i].y, 1))(0); } Vector<double> shear = least_squares(a, b); Matrix<double> interm = math::identity_matrix<3>(); interm(0, 1) = -shear[1] / 2.0; affine_left = interm * affine_left; interm = math::identity_matrix<3>(); interm(0, 0) = shear[0]; interm(0, 1) = shear[1] / 2.0; interm(0, 2) = shear[2]; affine_right = interm * affine_right; } // A functor which returns the best fit left and right 3x3 matrices // for epipolar alignment. Store them as a single 3x7 matrix. The // last column will have the upper-right corner of the intersections // of the domains of the left and right images with the resulting // transformed applied to them. struct BestFitEpipolarAlignment { Vector2i m_ldims, m_rdims; BestFitEpipolarAlignment(Vector2i const& left_image_dims, Vector2i const& right_image_dims): m_ldims(left_image_dims), m_rdims(right_image_dims) {} typedef vw::Matrix<double, 3, 7> result_type; /// The fundamental matrix needs 8 points. // TODO(oalexan1): Should a bigger minimum be used for robustness? template <class InterestPointT> size_t min_elements_needed_for_fit(InterestPointT const& /*example*/) const { return 8; } /// This function can match points in any container that supports /// the size() and operator[] methods. The container is usually a /// vw::Vector<>, but you could substitute other classes here as /// well. template <class InterestPointT> vw::Matrix<double> operator()(std::vector<InterestPointT> const& ip1, std::vector<InterestPointT> const& ip2, vw::Matrix<double> const& /*seed_input*/ = vw::Matrix<double>() ) const { // check consistency VW_ASSERT( ip1.size() == ip2.size(), vw::ArgumentErr() << "Cannot compute fundamental matrix. " << "ip1 and ip2 are not the same size." ); VW_ASSERT( !ip1.empty() && ip1.size() >= min_elements_needed_for_fit(ip1[0]), vw::ArgumentErr() << "Cannot compute fundamental matrix. " << "Need at at least 8 points, but got: " << ip1.size() << ".\n"); // Compute the affine fundamental matrix Matrix<double> fund = linear_affine_fundamental_matrix(ip1, ip2); // Solve for rotation matrices double Hl = sqrt(fund(2, 0)*fund(2, 0) + fund(2, 1)*fund(2, 1)); double Hr = sqrt(fund(0, 2)*fund(0, 2) + fund(1, 2)*fund(1, 2)); Vector2 epipole(-fund(2, 1), fund(2, 0)), epipole_prime(-fund(1, 2), fund(0, 2)); if (epipole.x() < 0) epipole = -epipole; if (epipole_prime.x() < 0) epipole_prime = -epipole_prime; epipole.y() = -epipole.y(); epipole_prime.y() = -epipole_prime.y(); Matrix<double> left_matrix = math::identity_matrix<3>(); Matrix<double> right_matrix = math::identity_matrix<3>(); left_matrix(0, 0) = epipole[0]/Hl; left_matrix(0, 1) = -epipole[1]/Hl; left_matrix(1, 0) = epipole[1]/Hl; left_matrix(1, 1) = epipole[0]/Hl; right_matrix(0, 0) = epipole_prime[0]/Hr; right_matrix(0, 1) = -epipole_prime[1]/Hr; right_matrix(1, 0) = epipole_prime[1]/Hr; right_matrix(1, 1) = epipole_prime[0]/Hr; // Solve for ideal scaling and translation solve_y_scaling(ip1, ip2, left_matrix, right_matrix); // Solve for ideal shear, scale, and translation of X axis solve_x_shear(ip1, ip2, left_matrix, right_matrix); // Work out the ideal render size BBox2i output_bbox, right_bbox; output_bbox.grow(subvector(left_matrix * Vector3(0, 0, 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(m_ldims.x(), 0, 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(m_ldims.x(), m_ldims.y(), 1), 0, 2)); output_bbox.grow(subvector(left_matrix * Vector3(0, m_ldims.y(), 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(0, 0, 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(m_rdims.x(), 0, 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(m_rdims.x(), m_rdims.y(), 1), 0, 2)); right_bbox.grow(subvector(right_matrix * Vector3(0, m_rdims.y(), 1), 0, 2)); output_bbox.crop(right_bbox); left_matrix (0, 2) -= output_bbox.min().x(); right_matrix(0, 2) -= output_bbox.min().x(); left_matrix (1, 2) -= output_bbox.min().y(); right_matrix(1, 2) -= output_bbox.min().y(); // Concatenate these into the answer result_type T; submatrix(T, 0, 0, 3, 3) = left_matrix; submatrix(T, 0, 3, 3, 3) = right_matrix; // Also save the domain after alignment T(0, 6) = output_bbox.width(); T(1, 6) = output_bbox.height(); return T; } }; // Find the absolute difference of the y components of the given // interest point pair after applying to those points the given // epipolar alignment matrices. If these matrices are correct, // and the interest point pair is not an outlier, this // absolute difference should be close to 0. struct EpipolarAlignmentError { template <class TransformT, class InterestPointT> double operator() (TransformT const& T, InterestPointT const& ip1, InterestPointT const& ip2) const { Matrix<double> left_matrix = submatrix(T, 0, 0, 3, 3); Matrix<double> right_matrix = submatrix(T, 0, 3, 3, 3); Vector3 L = left_matrix * Vector3(ip1.x, ip1.y, 1); Vector3 R = right_matrix * Vector3(ip2.x, ip2.y, 1); double diff = L[1] - R[1]; return std::abs(diff); } }; // Helper function to instantiate a RANSAC class object and immediately call it template <class ContainerT1, class ContainerT2, class FittingFuncT, class ErrorFuncT> typename FittingFuncT::result_type ransac(std::vector<ContainerT1> const& p1, std::vector<ContainerT2> const& p2, FittingFuncT const& fitting_func, ErrorFuncT const& error_func, int num_iterations, double inlier_threshold, int min_num_output_inliers, bool reduce_min_num_output_inliers_if_no_fit = false ) { RandomSampleConsensus<FittingFuncT, ErrorFuncT> ransac_instance(fitting_func, error_func, num_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit ); return ransac_instance(p1,p2); } // Main function that other parts of ASP should use Vector2i affine_epipolar_rectification(Vector2i const& left_image_dims, Vector2i const& right_image_dims, double inlier_threshold, int num_ransac_iterations, std::vector<ip::InterestPoint> const& ip1, std::vector<ip::InterestPoint> const& ip2, Matrix<double>& left_matrix, Matrix<double>& right_matrix, // optionally return the inliers std::vector<size_t> * inliers_ptr) { int min_num_output_inliers = ip1.size() / 2; bool reduce_min_num_output_inliers_if_no_fit = true; vw::Matrix<double> T; Stopwatch sw; sw.start(); vw_out() << "Computing the epipolar rectification " << "using RANSAC with " << num_ransac_iterations << " iterations and inlier threshold " << inlier_threshold << ".\n"; // If RANSAC fails, it will throw an exception BestFitEpipolarAlignment func(left_image_dims, right_image_dims); EpipolarAlignmentError error_metric; std::vector<size_t> inlier_indices; RandomSampleConsensus<BestFitEpipolarAlignment, EpipolarAlignmentError> ransac(func, error_metric, num_ransac_iterations, inlier_threshold, min_num_output_inliers, reduce_min_num_output_inliers_if_no_fit); T = ransac(ip1, ip2); inlier_indices = ransac.inlier_indices(T, ip1, ip2); vw_out() << "Found " << inlier_indices.size() << " / " << ip1.size() << " inliers.\n"; sw.stop(); vw_out(DebugMessage,"asp") << "Elapsed time in computing rectification matrices: " << sw.elapsed_seconds() << " seconds.\n"; // Extract the matrices and the cropped transformed box from the computed transform left_matrix = submatrix(T, 0, 0, 3, 3); right_matrix = submatrix(T, 0, 3, 3, 3); Vector2i trans_crop_box(T(0, 6), T(1, 6)); // Find the maximum error for inliers double max_err = 0.0; for (size_t it = 0; it < inlier_indices.size(); it++) { int i = inlier_indices[it]; max_err = std::max(max_err, error_metric(T, ip1[i], ip2[i])); } vw_out() << "Maximum absolute difference of y components of " << "aligned inlier interest points is " << max_err << " pixels." << std::endl; // Optionally return the inliers if (inliers_ptr != NULL) *inliers_ptr = inlier_indices; return trans_crop_box; } } // end namespace asp <|endoftext|>
<commit_before>/*************************************************************************** * @file order_statistic_tree.hpp * @author Alan.W * @date 20 July 2014 * @remark Implementation of CLRS algorithms, using C++ templates. ***************************************************************************/ //! //! 14.1-3 //! Write a nonrecursive version of OS-SELECT . //! #ifndef ORDER_STATISTIC_TREE_HPP #define ORDER_STATISTIC_TREE_HPP #include "red_black_tree.hpp" namespace ch14 { /** * @brief The OrderStatisticTree class * * inherited from Red Black Tree */ template<typename K, typename D> class OrderStatisticTree : public RedBlackTree<K,D> { public: using B = RedBlackTree<K,D>; using sPointer = typename B::sPointer; using SizeType = std::size_t; using B::insert; //! ^^^^^^^^^^^^^^^ -- needed to call this virtual function from base class /** * @brief select * * @complx O(lg n) * * @page 341 */ sPointer select(sPointer target, SizeType rank) { //! must be within the range. assert(rank <= target->size + 1); SizeType curr = target->rank(); if(rank == curr) return target; else return rank < curr? select(target->left,rank) : select(target->right, rank - curr); } /** * @brief select_norecur * * @complx O(lg n) * * ex14-1.3 */ sPointer select_norecur(sPointer target, SizeType rank) { //! must be within the range. assert(rank <= target->size + 1); SizeType r = target->rank(); while(r != rank) { if(rank < r) target = target->left; else { target = target->right; rank -= r; } r = target->rank(); } return target; } /** * @brief rank * return the rank within the whole tree * * @complx O(lg n) * * @page 342 */ SizeType rank(sPointer target) { SizeType ret = target->rank(); sPointer curr = target; while(curr != root) { if(curr->is_right()) ret += sibling(curr)->size + 1; curr = curr->parent.lock(); } return ret; } //! Dtor virtual ~OrderStatisticTree(){ } private: using B::root; using B::nil; using B::ascend; using B::sibling; using B::insert_fixup; /** * @brief left_rotate * @param x * * @attention virtual! * * @complx O(1) * * based on the pseudocode P343 */ virtual void left_rotate(sPointer x) override { B::left_rotate(x); sPointer parent = x->parent.lock(); parent->size = x->size; x->size = x->left->size + x->right->size + 1; } /** * @brief right_rotate * @param y * * @attention virtual! * * @complx O(1) */ virtual void right_rotate(sPointer y) override { B::right_rotate(y); sPointer parent = y->parent.lock(); parent->size = y->size; y->size = y->left->size + y->right->size + 1; } /** * @brief insert * @param added * * @attention virtual! * * @complx O(h) */ virtual void insert(sPointer added) override { sPointer tracker = nil; sPointer curr = root; while(curr != nil) { ++curr->size; //! ^^^^^^^^^^^^^ -- added for o s tree tracker = curr; curr = curr->key > added->key? curr->left : curr->right; } added->parent = tracker; if(tracker == nil) root = added; else (added->key < tracker->key? tracker->left : tracker->right) = added; added->left = added->right = nil; added->color= Color::RED; //! fixup insert_fixup(added); } }; }//namespace #endif // ORDER_STATISTIC_TREE_HPP //! for testing insert and remove //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // ch14::RedBlackTree<int, std::string>* // tree = // new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {3,4,1,5,6,2,7,0,10,65,23}; // for(auto i : v) // tree->insert(i); // std::cout << debug::red("deleting!!:\n"); // tree->remove(tree->search(4)); // tree->print(); // std::cout << debug::green("\nend\n"); // delete tree; // return 0; //} //! for testing select() //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // auto tree = new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("testing select:\n"); // auto node = tree->search(44); // auto ret = tree->select(node,7); // ret->print(); // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} //! testing rank() //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // using Tree = ch14::OrderStatisticTree<int, std::string>; // Tree* tree = new Tree; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("\ntesting rank:\n"); // auto node = tree->search(88); // std::cout << debug::green("the rank is: "); // std::cout << tree->rank(node) << std::endl; // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} //! for testing select_nonrecur required in ex14-1.3 //#include <iostream> //#include <string> //#include <vector> //#include "order_statistic_tree.hpp" //int main() //{ // auto tree = new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("testing select:\n"); // auto node = tree->search(44); // auto ret = tree->select_norecur(node,7); // ret->print(); // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} <commit_msg>added description for ex14.1-4 On branch ch14 modified: ch14/order_statistic_tree.hpp<commit_after>/*************************************************************************** * @file order_statistic_tree.hpp * @author Alan.W * @date 20 July 2014 * @remark Implementation of CLRS algorithms, using C++ templates. ***************************************************************************/ //! //! 14.1-3 //! Write a nonrecursive version of OS-SELECT . //! // as select_nonrecur shown in the code below //! //! 14.1-4 //! Write a recursive procedure OS-KEY-RANK(T,k) that takes as input an order- //! statistic tree T and a key k and returns the rank of k in the dynamic set represented //! by T . Assume that the keys of T are distinct. //! #ifndef ORDER_STATISTIC_TREE_HPP #define ORDER_STATISTIC_TREE_HPP #include "red_black_tree.hpp" namespace ch14 { /** * @brief The OrderStatisticTree class * * inherited from Red Black Tree */ template<typename K, typename D> class OrderStatisticTree : public RedBlackTree<K,D> { public: using B = RedBlackTree<K,D>; using sPointer = typename B::sPointer; using SizeType = std::size_t; using B::insert; //! ^^^^^^^^^^^^^^^ -- needed to call this virtual function from base class /** * @brief select * * @complx O(lg n) * * @page 341 */ sPointer select(sPointer target, SizeType rank) { //! must be within the range. assert(rank <= target->size + 1); SizeType curr = target->rank(); if(rank == curr) return target; else return rank < curr? select(target->left,rank) : select(target->right, rank - curr); } /** * @brief select_norecur * * @complx O(lg n) * * ex14-1.3 */ sPointer select_norecur(sPointer target, SizeType rank) { //! must be within the range. assert(rank <= target->size + 1); SizeType r = target->rank(); while(r != rank) { if(rank < r) target = target->left; else { target = target->right; rank -= r; } r = target->rank(); } return target; } /** * @brief rank * return the rank within the whole tree * * @complx O(lg n) * * @page 342 */ SizeType rank(sPointer target) { SizeType ret = target->rank(); sPointer curr = target; while(curr != root) { if(curr->is_right()) ret += sibling(curr)->size + 1; curr = curr->parent.lock(); } return ret; } //! Dtor virtual ~OrderStatisticTree(){ } private: using B::root; using B::nil; using B::ascend; using B::sibling; using B::insert_fixup; /** * @brief left_rotate * @param x * * @attention virtual! * * @complx O(1) * * based on the pseudocode P343 */ virtual void left_rotate(sPointer x) override { B::left_rotate(x); sPointer parent = x->parent.lock(); parent->size = x->size; x->size = x->left->size + x->right->size + 1; } /** * @brief right_rotate * @param y * * @attention virtual! * * @complx O(1) */ virtual void right_rotate(sPointer y) override { B::right_rotate(y); sPointer parent = y->parent.lock(); parent->size = y->size; y->size = y->left->size + y->right->size + 1; } /** * @brief insert * @param added * * @attention virtual! * * @complx O(h) */ virtual void insert(sPointer added) override { sPointer tracker = nil; sPointer curr = root; while(curr != nil) { ++curr->size; //! ^^^^^^^^^^^^^ -- added for o s tree tracker = curr; curr = curr->key > added->key? curr->left : curr->right; } added->parent = tracker; if(tracker == nil) root = added; else (added->key < tracker->key? tracker->left : tracker->right) = added; added->left = added->right = nil; added->color= Color::RED; //! fixup insert_fixup(added); } }; }//namespace #endif // ORDER_STATISTIC_TREE_HPP //! for testing insert and remove //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // ch14::RedBlackTree<int, std::string>* // tree = // new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {3,4,1,5,6,2,7,0,10,65,23}; // for(auto i : v) // tree->insert(i); // std::cout << debug::red("deleting!!:\n"); // tree->remove(tree->search(4)); // tree->print(); // std::cout << debug::green("\nend\n"); // delete tree; // return 0; //} //! for testing select() //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // auto tree = new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("testing select:\n"); // auto node = tree->search(44); // auto ret = tree->select(node,7); // ret->print(); // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} //! testing rank() //#include <iostream> //#include <string> //#include <memory> //#include <vector> //#include "red_black_tree.hpp" //#include "order_statistic_tree.hpp" //int main() //{ // using Tree = ch14::OrderStatisticTree<int, std::string>; // Tree* tree = new Tree; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("\ntesting rank:\n"); // auto node = tree->search(88); // std::cout << debug::green("the rank is: "); // std::cout << tree->rank(node) << std::endl; // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} //! for testing select_nonrecur required in ex14-1.3 //#include <iostream> //#include <string> //#include <vector> //#include "order_statistic_tree.hpp" //int main() //{ // auto tree = new ch14::OrderStatisticTree<int, std::string>; // std::vector<int> v = {11,22,33,44,55,66,77,88}; // for(auto i : v) // tree->insert(i); // tree->print(); // std::cout << debug::red("testing select:\n"); // auto node = tree->search(44); // auto ret = tree->select_norecur(node,7); // ret->print(); // delete tree; // std::cout << debug::green("\nend\n"); // return 0; //} <|endoftext|>
<commit_before>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the Mp3AudioSource class. * @see audio/audio_source.hpp */ #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> extern "C" { #include <mpg123.h> } #include "../errors.hpp" #include "../messages.h" #include "../sample_formats.hpp" #include "audio_source.hpp" // This value is somewhat arbitrary, but corresponds to the minimum buffer size // used by ffmpeg, so it's probably sensible. const size_t Mp3AudioSource::BUFFER_SIZE = 16384; Mp3AudioSource::Mp3AudioSource(const std::string &path) : buffer(BUFFER_SIZE), context(nullptr), path(path) { this->context = mpg123_new(nullptr, nullptr); mpg123_format_none(this->context); const long *rates = nullptr; size_t nrates = 0; mpg123_rates(&rates, &nrates); for (size_t r = 0; r < nrates; r++) { Debug() << "trying to enable formats at " << rates[r] << std::endl; AddFormat(rates[r]); } if (mpg123_open(this->context, path.c_str()) == MPG123_ERR) { throw FileError("mp3: can't open " + path + ": " + mpg123_strerror(this->context)); } Debug() << "mp3: sample rate:" << this->SampleRate() << std::endl; Debug() << "mp3: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "mp3: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "mp3: playd format:" << (int)this->OutputSampleFormat() << std::endl; } Mp3AudioSource::~Mp3AudioSource() { mpg123_delete(this->context); this->context = nullptr; } void Mp3AudioSource::AddFormat(long rate) { // The requested encodings correspond to the sample formats available in // the SampleFormat enum. if (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO, (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) == MPG123_ERR) { // Ignore the error for now -- another sample rate may be available. // If no sample rates work, loading a file will fail anyway. Debug() << "can't support " << rate << std::endl; }; } std::string Mp3AudioSource::Path() const { return this->path; } std::uint8_t Mp3AudioSource::ChannelCount() const { assert(this->context != nullptr); long rate = 0; int chans = 0; int encoding = 0; mpg123_getformat(this->context, &rate, &chans, &encoding); assert(chans != 0); return static_cast<std::uint8_t>(chans); } double Mp3AudioSource::SampleRate() const { assert(this->context != nullptr); long rate = 0; int chans = 0; int encoding = 0; mpg123_getformat(this->context, &rate, &chans, &encoding); return static_cast<double>(rate); } size_t Mp3AudioSource::BytesPerSample() const { assert(this->context != nullptr); long rate = 0; int chans = 0; int encoding = 0; mpg123_getformat(this->context, &rate, &chans, &encoding); auto es = mpg123_encsize(encoding); assert(es != 0); // mpg123_encsize returns bytes per mono sample, so we need to // convert to bytes per all-channels sample. // All of mpg123's samples counts are like this, so you'll see this // pattern all over the class. return es * this->ChannelCount(); } std::uint64_t Mp3AudioSource::Seek(std::uint64_t position) { assert(this->context != nullptr); auto samples = this->SamplesFromMicros(position); // See BytesPerSample() for an explanation of this ChannelCount(). auto mono_samples = samples * this->ChannelCount(); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(mpg123_length(this->context)); if (clen < mono_samples) { Debug() << "mp3: seek at" << mono_samples << "past EOF at" << clen << std::endl; Debug() << "mp3: requested position micros:" << position << std::endl; throw SeekError(MSG_SEEK_FAIL); } if (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) { Debug() << "mp3: seek failed:" << mpg123_strerror(this->context) << std::endl; throw SeekError(MSG_SEEK_FAIL); } // Reset the decoder state, because otherwise the decoder will get very // confused. this->decode_state = DecodeState::DECODING; // The actual seek position may not be the same as the requested // position. // mpg123_tell gives us the exact mono-samples position. return mpg123_tell(this->context) / this->ChannelCount(); } Mp3AudioSource::DecodeResult Mp3AudioSource::Decode() { assert(this->context != nullptr); auto buf = reinterpret_cast<unsigned char *>(&this->buffer.front()); size_t rbytes = 0; int err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes); DecodeVector decoded; if (err == MPG123_DONE) { Debug() << "mp3: end of file" << std::endl; this->decode_state = DecodeState::END_OF_FILE; } else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) { Debug() << "mp3: decode error:" << mpg123_strerror(this->context) << std::endl; this->decode_state = DecodeState::END_OF_FILE; } else { this->decode_state = DecodeState::DECODING; // Copy only the bit of the buffer occupied by decoded data auto front = this->buffer.begin(); decoded = DecodeVector(front, front + rbytes); } return std::make_pair(this->decode_state, decoded); } SampleFormat Mp3AudioSource::OutputSampleFormat() const { assert(this->context != nullptr); long rate = 0; int chans = 0; int encoding = 0; mpg123_getformat(this->context, &rate, &chans, &encoding); switch (encoding) { case MPG123_ENC_UNSIGNED_8: return SampleFormat::PACKED_UNSIGNED_INT_8; case MPG123_ENC_SIGNED_16: return SampleFormat::PACKED_SIGNED_INT_16; case MPG123_ENC_SIGNED_32: return SampleFormat::PACKED_SIGNED_INT_32; case MPG123_ENC_FLOAT_32: return SampleFormat::PACKED_FLOAT_32; default: // We shouldn't get here, if the format was set up // correctly earlier. assert(false); } }<commit_msg>Don't getformat() things we don't need.<commit_after>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the Mp3AudioSource class. * @see audio/audio_source.hpp */ #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> extern "C" { #include <mpg123.h> } #include "../errors.hpp" #include "../messages.h" #include "../sample_formats.hpp" #include "audio_source.hpp" // This value is somewhat arbitrary, but corresponds to the minimum buffer size // used by ffmpeg, so it's probably sensible. const size_t Mp3AudioSource::BUFFER_SIZE = 16384; Mp3AudioSource::Mp3AudioSource(const std::string &path) : buffer(BUFFER_SIZE), context(nullptr), path(path) { this->context = mpg123_new(nullptr, nullptr); mpg123_format_none(this->context); const long *rates = nullptr; size_t nrates = 0; mpg123_rates(&rates, &nrates); for (size_t r = 0; r < nrates; r++) { Debug() << "trying to enable formats at " << rates[r] << std::endl; AddFormat(rates[r]); } if (mpg123_open(this->context, path.c_str()) == MPG123_ERR) { throw FileError("mp3: can't open " + path + ": " + mpg123_strerror(this->context)); } Debug() << "mp3: sample rate:" << this->SampleRate() << std::endl; Debug() << "mp3: bytes per sample:" << this->BytesPerSample() << std::endl; Debug() << "mp3: channels:" << (int)this->ChannelCount() << std::endl; Debug() << "mp3: playd format:" << (int)this->OutputSampleFormat() << std::endl; } Mp3AudioSource::~Mp3AudioSource() { mpg123_delete(this->context); this->context = nullptr; } void Mp3AudioSource::AddFormat(long rate) { // The requested encodings correspond to the sample formats available in // the SampleFormat enum. if (mpg123_format(this->context, rate, MPG123_STEREO | MPG123_MONO, (MPG123_ENC_UNSIGNED_8 | MPG123_ENC_SIGNED_16 | MPG123_ENC_SIGNED_32 | MPG123_ENC_FLOAT_32)) == MPG123_ERR) { // Ignore the error for now -- another sample rate may be available. // If no sample rates work, loading a file will fail anyway. Debug() << "can't support" << rate << std::endl; }; } std::string Mp3AudioSource::Path() const { return this->path; } std::uint8_t Mp3AudioSource::ChannelCount() const { assert(this->context != nullptr); int chans = 0; mpg123_getformat(this->context, nullptr, &chans, nullptr); assert(chans != 0); return static_cast<std::uint8_t>(chans); } double Mp3AudioSource::SampleRate() const { assert(this->context != nullptr); long rate = 0; mpg123_getformat(this->context, &rate, nullptr, nullptr); assert(rate != 0); return static_cast<double>(rate); } size_t Mp3AudioSource::BytesPerSample() const { assert(this->context != nullptr); int encoding = 0; mpg123_getformat(this->context, nullptr, nullptr, &encoding); auto es = mpg123_encsize(encoding); assert(es != 0); // mpg123_encsize returns bytes per mono sample, so we need to // convert to bytes per all-channels sample. // All of mpg123's samples counts are like this, so you'll see this // pattern all over the class. return es * this->ChannelCount(); } std::uint64_t Mp3AudioSource::Seek(std::uint64_t position) { assert(this->context != nullptr); auto samples = this->SamplesFromMicros(position); // See BytesPerSample() for an explanation of this ChannelCount(). auto mono_samples = samples * this->ChannelCount(); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(mpg123_length(this->context)); if (clen < mono_samples) { Debug() << "mp3: seek at" << mono_samples << "past EOF at" << clen << std::endl; Debug() << "mp3: requested position micros:" << position << std::endl; throw SeekError(MSG_SEEK_FAIL); } if (mpg123_seek(this->context, mono_samples, SEEK_SET) == MPG123_ERR) { Debug() << "mp3: seek failed:" << mpg123_strerror(this->context) << std::endl; throw SeekError(MSG_SEEK_FAIL); } // Reset the decoder state, because otherwise the decoder will get very // confused. this->decode_state = DecodeState::DECODING; // The actual seek position may not be the same as the requested // position. // mpg123_tell gives us the exact mono-samples position. return mpg123_tell(this->context) / this->ChannelCount(); } Mp3AudioSource::DecodeResult Mp3AudioSource::Decode() { assert(this->context != nullptr); auto buf = reinterpret_cast<unsigned char *>(&this->buffer.front()); size_t rbytes = 0; int err = mpg123_read(this->context, buf, this->buffer.size(), &rbytes); DecodeVector decoded; if (err == MPG123_DONE) { Debug() << "mp3: end of file" << std::endl; this->decode_state = DecodeState::END_OF_FILE; } else if (err != MPG123_OK && err != MPG123_NEW_FORMAT) { Debug() << "mp3: decode error:" << mpg123_strerror(this->context) << std::endl; this->decode_state = DecodeState::END_OF_FILE; } else { this->decode_state = DecodeState::DECODING; // Copy only the bit of the buffer occupied by decoded data auto front = this->buffer.begin(); decoded = DecodeVector(front, front + rbytes); } return std::make_pair(this->decode_state, decoded); } SampleFormat Mp3AudioSource::OutputSampleFormat() const { assert(this->context != nullptr); int encoding = 0; mpg123_getformat(this->context, nullptr, nullptr, &encoding); switch (encoding) { case MPG123_ENC_UNSIGNED_8: return SampleFormat::PACKED_UNSIGNED_INT_8; case MPG123_ENC_SIGNED_16: return SampleFormat::PACKED_SIGNED_INT_16; case MPG123_ENC_SIGNED_32: return SampleFormat::PACKED_SIGNED_INT_32; case MPG123_ENC_FLOAT_32: return SampleFormat::PACKED_FLOAT_32; default: // We shouldn't get here, if the format was set up // correctly earlier. assert(false); } }<|endoftext|>
<commit_before>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "ChaperoneData.h" // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <osvr/Util/Finally.h> // Standard includes #include <fstream> #include <functional> #include <iostream> #include <map> #include <sstream> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define NO_MINMAX #include <windows.h> static inline std::string formatLastErrorAsString() { char *lpMsgBuf = nullptr; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language reinterpret_cast<LPSTR>(&lpMsgBuf), 0, nullptr); /// Free that buffer when we're out of scope. auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); }); auto errorMessage = std::string(lpMsgBuf); return errorMessage; } static inline std::string getFile(std::string const &fn, std::function<void(std::string const &)> const &errorReport) { /// Had trouble with "permission denied" errors using standard C++ iostreams /// on the chaperone data, so had to go back down to Win32 API. HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == f) { errorReport("Could not open file: " + formatLastErrorAsString()); return std::string{}; } auto closer = osvr::util::finally([&f] { CloseHandle(f); }); std::ostringstream os; static const auto BUFSIZE = 1024; std::array<char, BUFSIZE + 1> buf; /// Null terminate for ease of use. buf.back() = '\0'; bool keepReading = true; while (1) { DWORD bytesRead; auto ret = ReadFile(f, buf.data(), buf.size() - 1, &bytesRead, nullptr); if (ret) { if (bytesRead == 0) { // end of file break; } else { // Null terminate this block and slide it in. // std::cout << "read " << bytesRead << " bytes this time " // << std::endl; buf[bytesRead] = '\0'; os << buf.data(); } } else { errorReport("Error after reading " + std::to_string(os.str().size()) + " bytes: " + formatLastErrorAsString()); return std::string{}; } } return os.str(); } #else std::string getFile(std::string const &fn, std::function<void(std::string const &)> const &errorReport) { std::ifstream s(fn, std::ios::in | std::ios::binary); if (!s) { std::ostringstream os; os << "Could not open file "; /// Sadly errno is far more useful in its error messages than /// failbit-triggered exceptions, etc. auto theErrno = errno; os << " (Error code: " << theErrno << " - " << strerror(theErrno) << ")"; errorReport(os.str()); return std::string{}; } std::ostringstream os; std::string temp; while (std::getline(os, temp)) { os << temp; } return os.str(); } #endif namespace osvr { namespace vive { static const auto PREFIX = "[ChaperoneData] "; static const auto CHAPERONE_DATA_FILENAME = "chaperone_info.vrchap"; #ifdef _WIN32 static const auto PATH_SEPARATOR = "\\"; #else static const auto PATH_SEPARATOR = "/"; #endif using UniverseDataMap = std::map<std::uint64_t, ChaperoneData::UniverseData>; struct ChaperoneData::Impl { Json::Value chaperoneInfo; UniverseDataMap universes; }; ChaperoneData::ChaperoneData(std::string const &steamConfigDir) : impl_(new Impl), configDir_(steamConfigDir) { { Json::Reader reader; auto chapInfoFn = configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME; #if 0 std::ifstream chapInfoFile(configDir_, std::ios::in | std::ios::binary); if (!chapInfoFile) { std::ostringstream os; os << "Could not open chaperone info file, expected at " << chapInfoFn; /// Sadly errno is far more useful in its error messages than /// failbit-triggered exceptions, etc. auto theErrno = errno; os << " (Error code: " << theErrno << " - " << strerror(theErrno) << ")"; errorOut_(os.str()); return; } if (!chapInfoFile.good()) { errorOut_("Could not open chaperone info file, expected at " + chapInfoFn); return; } #endif std::string fileData = getFile(chapInfoFn, [&](std::string const &message) { std::ostringstream os; os << "Could not open chaperone info file, expected at " << chapInfoFn; os << " - details [" << message << "]"; errorOut_(os.str()); }); if (!valid()) { /// this means our fail handler got called. return; } if (!reader.parse(fileData, impl_->chaperoneInfo)) { errorOut_("Could not parse JSON in chaperone info file at " + chapInfoFn + ": " + reader.getFormattedErrorMessages()); return; } /// Basic sanity checks if (impl_->chaperoneInfo["jsonid"] != "chaperone_info") { errorOut_("Chaperone info file at " + chapInfoFn + " did not match expected format (no element " "\"jsonid\": \"chaperone_info\" in top level " "object)"); return; } if (impl_->chaperoneInfo["universes"].size() == 0) { errorOut_("Chaperone info file at " + chapInfoFn + " did not contain any known chaperone universes - " "user must run Room Setup at least once"); return; } } for (auto const &univ : impl_->chaperoneInfo["universes"]) { auto univIdString = univ["universeID"].asString(); auto &standing = univ["standing"]; if (standing.isNull()) { warn_("No standing calibration data for universe " + univIdString + ", so had to skip it."); continue; } std::uint64_t id; std::istringstream is(univIdString); is >> id; UniverseData data; data.yaw = standing["yaw"].asDouble(); auto &xlate = standing["translation"]; for (std::size_t i = 0; i < 3; ++i) { data.translation[i] = xlate[i].asDouble(); } impl_->universes.insert(std::make_pair(id, data)); } } ChaperoneData::~ChaperoneData() {} bool ChaperoneData::valid() const { return static_cast<bool>(impl_); } bool ChaperoneData::knowUniverseId(std::uint64_t universe) const { if (0 == universe) { return false; } return (impl_->universes.find(universe) != end(impl_->universes)); } ChaperoneData::UniverseData ChaperoneData::getDataForUniverse(std::uint64_t universe) const { auto it = impl_->universes.find(universe); if (it == end(impl_->universes)) { return UniverseData(); } return it->second; } std::size_t ChaperoneData::getNumberOfKnownUniverses() const { return impl_->universes.size(); } void ChaperoneData::errorOut_(std::string const &message) { /// This reset may be redundant in some cases, but better to not miss /// it, since it's also our error flag. impl_.reset(); warn_("ERROR: " + message); } void ChaperoneData::warn_(std::string const &message) { if (err_.empty()) { /// First error err_ = message; return; } static const auto BEGIN_LIST = "["; static const auto BEGIN_LIST_CH = BEGIN_LIST[0]; static const auto END_LIST = "]"; static const auto MIDDLE_LIST = "]["; if (BEGIN_LIST_CH == err_.front()) { /// We've already started a list of errors, just tack one more on. err_ += BEGIN_LIST + message + END_LIST; return; } /// OK, so this is our exactly second error, wrap the first and second. err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST; } } // namespace vive } // namespace osvr<commit_msg>Fix ambiguity in 64-bit build.<commit_after>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "ChaperoneData.h" // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <osvr/Util/Finally.h> // Standard includes #include <fstream> #include <functional> #include <iostream> #include <map> #include <sstream> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define NO_MINMAX #include <windows.h> static inline std::string formatLastErrorAsString() { char *lpMsgBuf = nullptr; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language reinterpret_cast<LPSTR>(&lpMsgBuf), 0, nullptr); /// Free that buffer when we're out of scope. auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); }); auto errorMessage = std::string(lpMsgBuf); return errorMessage; } static inline std::string getFile(std::string const &fn, std::function<void(std::string const &)> const &errorReport) { /// Had trouble with "permission denied" errors using standard C++ iostreams /// on the chaperone data, so had to go back down to Win32 API. HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == f) { errorReport("Could not open file: " + formatLastErrorAsString()); return std::string{}; } auto closer = osvr::util::finally([&f] { CloseHandle(f); }); std::ostringstream os; static const auto BUFSIZE = 1024; std::array<char, BUFSIZE + 1> buf; /// Null terminate for ease of use. buf.back() = '\0'; bool keepReading = true; while (1) { DWORD bytesRead; auto ret = ReadFile(f, buf.data(), buf.size() - 1, &bytesRead, nullptr); if (ret) { if (bytesRead == 0) { // end of file break; } else { // Null terminate this block and slide it in. // std::cout << "read " << bytesRead << " bytes this time " // << std::endl; buf[bytesRead] = '\0'; os << buf.data(); } } else { errorReport("Error after reading " + std::to_string(os.str().size()) + " bytes: " + formatLastErrorAsString()); return std::string{}; } } return os.str(); } #else std::string getFile(std::string const &fn, std::function<void(std::string const &)> const &errorReport) { std::ifstream s(fn, std::ios::in | std::ios::binary); if (!s) { std::ostringstream os; os << "Could not open file "; /// Sadly errno is far more useful in its error messages than /// failbit-triggered exceptions, etc. auto theErrno = errno; os << " (Error code: " << theErrno << " - " << strerror(theErrno) << ")"; errorReport(os.str()); return std::string{}; } std::ostringstream os; std::string temp; while (std::getline(os, temp)) { os << temp; } return os.str(); } #endif namespace osvr { namespace vive { static const auto PREFIX = "[ChaperoneData] "; static const auto CHAPERONE_DATA_FILENAME = "chaperone_info.vrchap"; #ifdef _WIN32 static const auto PATH_SEPARATOR = "\\"; #else static const auto PATH_SEPARATOR = "/"; #endif using UniverseDataMap = std::map<std::uint64_t, ChaperoneData::UniverseData>; struct ChaperoneData::Impl { Json::Value chaperoneInfo; UniverseDataMap universes; }; ChaperoneData::ChaperoneData(std::string const &steamConfigDir) : impl_(new Impl), configDir_(steamConfigDir) { { Json::Reader reader; auto chapInfoFn = configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME; #if 0 std::ifstream chapInfoFile(configDir_, std::ios::in | std::ios::binary); if (!chapInfoFile) { std::ostringstream os; os << "Could not open chaperone info file, expected at " << chapInfoFn; /// Sadly errno is far more useful in its error messages than /// failbit-triggered exceptions, etc. auto theErrno = errno; os << " (Error code: " << theErrno << " - " << strerror(theErrno) << ")"; errorOut_(os.str()); return; } if (!chapInfoFile.good()) { errorOut_("Could not open chaperone info file, expected at " + chapInfoFn); return; } #endif std::string fileData = getFile(chapInfoFn, [&](std::string const &message) { std::ostringstream os; os << "Could not open chaperone info file, expected at " << chapInfoFn; os << " - details [" << message << "]"; errorOut_(os.str()); }); if (!valid()) { /// this means our fail handler got called. return; } if (!reader.parse(fileData, impl_->chaperoneInfo)) { errorOut_("Could not parse JSON in chaperone info file at " + chapInfoFn + ": " + reader.getFormattedErrorMessages()); return; } /// Basic sanity checks if (impl_->chaperoneInfo["jsonid"] != "chaperone_info") { errorOut_("Chaperone info file at " + chapInfoFn + " did not match expected format (no element " "\"jsonid\": \"chaperone_info\" in top level " "object)"); return; } if (impl_->chaperoneInfo["universes"].size() == 0) { errorOut_("Chaperone info file at " + chapInfoFn + " did not contain any known chaperone universes - " "user must run Room Setup at least once"); return; } } for (auto const &univ : impl_->chaperoneInfo["universes"]) { auto univIdString = univ["universeID"].asString(); auto &standing = univ["standing"]; if (standing.isNull()) { warn_("No standing calibration data for universe " + univIdString + ", so had to skip it."); continue; } std::uint64_t id; std::istringstream is(univIdString); is >> id; UniverseData data; data.yaw = standing["yaw"].asDouble(); auto &xlate = standing["translation"]; for (Json::Value::ArrayIndex i = 0; i < 3; ++i) { data.translation[i] = xlate[i].asDouble(); } impl_->universes.insert(std::make_pair(id, data)); } } ChaperoneData::~ChaperoneData() {} bool ChaperoneData::valid() const { return static_cast<bool>(impl_); } bool ChaperoneData::knowUniverseId(std::uint64_t universe) const { if (0 == universe) { return false; } return (impl_->universes.find(universe) != end(impl_->universes)); } ChaperoneData::UniverseData ChaperoneData::getDataForUniverse(std::uint64_t universe) const { auto it = impl_->universes.find(universe); if (it == end(impl_->universes)) { return UniverseData(); } return it->second; } std::size_t ChaperoneData::getNumberOfKnownUniverses() const { return impl_->universes.size(); } void ChaperoneData::errorOut_(std::string const &message) { /// This reset may be redundant in some cases, but better to not miss /// it, since it's also our error flag. impl_.reset(); warn_("ERROR: " + message); } void ChaperoneData::warn_(std::string const &message) { if (err_.empty()) { /// First error err_ = message; return; } static const auto BEGIN_LIST = "["; static const auto BEGIN_LIST_CH = BEGIN_LIST[0]; static const auto END_LIST = "]"; static const auto MIDDLE_LIST = "]["; if (BEGIN_LIST_CH == err_.front()) { /// We've already started a list of errors, just tack one more on. err_ += BEGIN_LIST + message + END_LIST; return; } /// OK, so this is our exactly second error, wrap the first and second. err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST; } } // namespace vive } // namespace osvr<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/regex.h> #include <boost/algorithm/string/regex.hpp> #include <bitset> #include <regex> using boost::asio::ip::tcp; using namespace std; class Client { public: //public client entry point void Start(string endPoint, string filename) { try { Create(endPoint); boost::asio::connect(*this->_socket, this->_endpoint_iterator); cout << "Connected to host at " << endPoint << endl; Read(filename); } catch (exception &e) { cerr << e.what() << endl; } } private: boost::asio::io_service _IOService; tcp::resolver *_resolver; tcp::resolver::query *_query; tcp::resolver::iterator _endpoint_iterator; tcp::socket *_socket; //creates endpoint for client void Create(string endPoint) { this->_resolver = new tcp::resolver(this->_IOService); this->_query = new tcp::resolver::query(endPoint, "daytime"); this->_endpoint_iterator = (*this->_resolver).resolve(*this->_query); this->_socket = new tcp::socket(this->_IOService); } //receives data from server void Read(string filename) { string receivedData = ""; vector<string> data; cout << "Reveiving data..." << endl; for (;;) { boost::array<char, 20000> buf; boost::system::error_code error; size_t len = (*this->_socket).read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. for (int i = 0; i < len; i++) receivedData += buf.at(i); data.push_back(receivedData); receivedData.clear(); } for each (string str in data) { cout << "data: " << str << endl; } SaveToFile(filename, data); (*this->_socket).close(); cout << "Connection to server closed." << endl; } //saves transmitted data from server to file void SaveToFile(string filename, vector<string> receivedData) { ofstream stream; stream.open(filename); if (stream.good()) { cout << "Saving data to " << filename << "..." << endl; for each (auto str in receivedData) { if (str != "") stream << str << endl; } } else cerr << "ERROR: Could not open file: " << filename << endl; stream.close(); } };<commit_msg>fixed spelling mistake<commit_after>#include <iostream> #include <fstream> #include <boost/array.hpp> #include <boost/asio.hpp> #include <boost/regex.h> #include <boost/algorithm/string/regex.hpp> #include <bitset> #include <regex> using boost::asio::ip::tcp; using namespace std; class Client { public: //public client entry point void Start(string endPoint, string filename) { try { Create(endPoint); boost::asio::connect(*this->_socket, this->_endpoint_iterator); cout << "Connected to host at " << endPoint << endl; Read(filename); } catch (exception &e) { cerr << e.what() << endl; } } private: boost::asio::io_service _IOService; tcp::resolver *_resolver; tcp::resolver::query *_query; tcp::resolver::iterator _endpoint_iterator; tcp::socket *_socket; //creates endpoint for client void Create(string endPoint) { this->_resolver = new tcp::resolver(this->_IOService); this->_query = new tcp::resolver::query(endPoint, "daytime"); this->_endpoint_iterator = (*this->_resolver).resolve(*this->_query); this->_socket = new tcp::socket(this->_IOService); } //receives data from server void Read(string filename) { string receivedData = ""; vector<string> data; cout << "Receiving data..." << endl; for (;;) { boost::array<char, 20000> buf; boost::system::error_code error; size_t len = (*this->_socket).read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. for (int i = 0; i < len; i++) receivedData += buf.at(i); data.push_back(receivedData); receivedData.clear(); } for each (string str in data) { cout << "data: " << str << endl; } SaveToFile(filename, data); (*this->_socket).close(); cout << "Connection to server closed." << endl; } //saves transmitted data from server to file void SaveToFile(string filename, vector<string> receivedData) { ofstream stream; stream.open(filename); if (stream.good()) { cout << "Saving data to " << filename << "..." << endl; for each (auto str in receivedData) { if (str != "") stream << str << endl; } } else cerr << "ERROR: Could not open file: " << filename << endl; stream.close(); } }; <|endoftext|>
<commit_before>/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include "database.h" #include "config.h" #include <QtCore/QVariant> #include <QtCore/QDebug> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QtSql/QSqlRecord> /** * @brief Constructor. */ Database::Database( const QString &network, const QString &dbType, const QString &databaseName, const QString &username, const QString &password, const QString &hostname, int port, const QString &options ) : network_(network.toLower()) , db_(QSqlDatabase::addDatabase(typeToQtPlugin(dbType))) { db_.setDatabaseName( databaseName ); db_.setUserName( username ); db_.setPassword( password ); db_.setHostName( hostname ); db_.setPort( port ); db_.setConnectOptions( options ); } /** * @brief Destructor. */ Database::~Database() { } /** * @brief Create a Database from database configuration. */ Database *Database::fromConfig(const DatabaseConfig *dbc) { return new Database( "", dbc->type, dbc->database, dbc->username, dbc->password, dbc->hostname, dbc->port, dbc->options ); } /** * @brief Returns the last error in the QSqlDatabase object. */ QSqlError Database::lastError() const { return db_.lastError(); } /** * @brief Returns the network for which this Database was created. */ const QString &Database::network() const { return network_; } bool Database::open() { return db_.open(); } /** * @brief Retrieve property from database. * * The most specific scope will be selected first, i.e. user-specific scope. * If that yields no results, channel-specific scope will be returned, then * network-specific scope, then global scope. * * Variable should be formatted using reverse-domain format, i.e. for the * plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one * could use: * <code>net.jondoe.myfirstplugin.foo</code> */ QVariant Database::property( const QString &variable, const QString &networkScope, const QString &receiverScope, const QString &senderScope ) const { // retrieve from database QSqlQuery data(db_); data.prepare("SELECT value FROM properties WHERE variable=:var" " AND networkScope=:net AND receiverScope=:rcv" " AND senderScope=:snd"); data.bindValue(":var",variable); data.bindValue(":net",networkScope); data.bindValue(":rcv",receiverScope); data.bindValue(":snd",senderScope); // first, ask for most specific... if( !networkScope.isEmpty() && !receiverScope.isEmpty() && !senderScope.isEmpty() ) { data.exec(); if( data.next() ) return data.value(0); data.finish(); } // then, ask for channel specific if( !networkScope.isEmpty() && !receiverScope.isEmpty() ) { data.bindValue(":snd",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); } // ask for network specific if( !networkScope.isEmpty() ) { data.bindValue(":rcv",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); } // global property, then data.bindValue(":net",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); // nothing found, still? return null return QVariant(); } void Database::setProperty( const QString &variable, const QVariant &value, const QString &networkScope, const QString &receiverScope, const QString &senderScope ) { // set in database QSqlQuery data(db_); data.prepare("INSERT INTO properties (variable,value,network,receiver,sender)" /* " VALUES (:var, :val, :net, :rcv, :snd)"); data.bindValue(":var", variable); data.bindValue(":val", value); data.bindValue(":net", networkScope.isEmpty() ? QVariant() : networkScope); data.bindValue(":rcv", receiverScope.isEmpty() ? QVariant() : receiverScope); data.bindValue(":snd", senderScope.isEmpty() ? QVariant() : senderScope);*/ " VALUES (?, ?, ?, ?, ?)"); data.addBindValue(variable); data.addBindValue(value); data.addBindValue(networkScope.isEmpty() ? QVariant() : networkScope); data.addBindValue(receiverScope.isEmpty() ? QVariant() : receiverScope); data.addBindValue(senderScope.isEmpty() ? QVariant() : senderScope); if( !data.exec() ) { qWarning() << "Set property failed: " << data.lastError(); } } bool Database::createTable() { if( tableExists() ) return true; // database already exists QSqlQuery data(db_); return data.exec("CREATE TABLE properties (" " variable TEXT," " network TEXT," " receiver TEXT," " sender TEXT," " value TEXT" ");"); } bool Database::tableExists() const { return db_.record("properties").count() > 0; } QString Database::typeToQtPlugin(const QString &type) { if( type.toLower() == "sqlite" ) return "QSQLITE"; if( type.toLower() == "mysql" ) return "QMYSQL"; qWarning() << "typeToQtPlugin: Unknown type: " << type; return ""; } <commit_msg>Add id primary key in properties table, changed most TEXTs to VARCHARs.<commit_after>/** * Copyright (c) Sjors Gielen, 2010 * See LICENSE for license. */ #include "database.h" #include "config.h" #include <QtCore/QVariant> #include <QtCore/QDebug> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> #include <QtSql/QSqlRecord> /** * @brief Constructor. */ Database::Database( const QString &network, const QString &dbType, const QString &databaseName, const QString &username, const QString &password, const QString &hostname, int port, const QString &options ) : network_(network.toLower()) , db_(QSqlDatabase::addDatabase(typeToQtPlugin(dbType))) { db_.setDatabaseName( databaseName ); db_.setUserName( username ); db_.setPassword( password ); db_.setHostName( hostname ); db_.setPort( port ); db_.setConnectOptions( options ); } /** * @brief Destructor. */ Database::~Database() { } /** * @brief Create a Database from database configuration. */ Database *Database::fromConfig(const DatabaseConfig *dbc) { return new Database( "", dbc->type, dbc->database, dbc->username, dbc->password, dbc->hostname, dbc->port, dbc->options ); } /** * @brief Returns the last error in the QSqlDatabase object. */ QSqlError Database::lastError() const { return db_.lastError(); } /** * @brief Returns the network for which this Database was created. */ const QString &Database::network() const { return network_; } bool Database::open() { return db_.open(); } /** * @brief Retrieve property from database. * * The most specific scope will be selected first, i.e. user-specific scope. * If that yields no results, channel-specific scope will be returned, then * network-specific scope, then global scope. * * Variable should be formatted using reverse-domain format, i.e. for the * plugin MyFirstPlugin created by John Doe, to save a 'foo' variable one * could use: * <code>net.jondoe.myfirstplugin.foo</code> */ QVariant Database::property( const QString &variable, const QString &networkScope, const QString &receiverScope, const QString &senderScope ) const { // retrieve from database QSqlQuery data(db_); data.prepare("SELECT value FROM properties WHERE variable=:var" " AND networkScope=:net AND receiverScope=:rcv" " AND senderScope=:snd"); data.bindValue(":var",variable); data.bindValue(":net",networkScope); data.bindValue(":rcv",receiverScope); data.bindValue(":snd",senderScope); // first, ask for most specific... if( !networkScope.isEmpty() && !receiverScope.isEmpty() && !senderScope.isEmpty() ) { data.exec(); if( data.next() ) return data.value(0); data.finish(); } // then, ask for channel specific if( !networkScope.isEmpty() && !receiverScope.isEmpty() ) { data.bindValue(":snd",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); } // ask for network specific if( !networkScope.isEmpty() ) { data.bindValue(":rcv",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); } // global property, then data.bindValue(":net",QVariant()); data.exec(); if( data.next() ) return data.value(0); data.finish(); // nothing found, still? return null return QVariant(); } void Database::setProperty( const QString &variable, const QVariant &value, const QString &networkScope, const QString &receiverScope, const QString &senderScope ) { // set in database QSqlQuery data(db_); data.prepare("INSERT INTO properties (variable,value,network,receiver,sender)" /* " VALUES (:var, :val, :net, :rcv, :snd)"); data.bindValue(":var", variable); data.bindValue(":val", value); data.bindValue(":net", networkScope.isEmpty() ? QVariant() : networkScope); data.bindValue(":rcv", receiverScope.isEmpty() ? QVariant() : receiverScope); data.bindValue(":snd", senderScope.isEmpty() ? QVariant() : senderScope);*/ " VALUES (?, ?, ?, ?, ?)"); data.addBindValue(variable); data.addBindValue(value); data.addBindValue(networkScope.isEmpty() ? QVariant() : networkScope); data.addBindValue(receiverScope.isEmpty() ? QVariant() : receiverScope); data.addBindValue(senderScope.isEmpty() ? QVariant() : senderScope); if( !data.exec() ) { qWarning() << "Set property failed: " << data.lastError(); } } bool Database::createTable() { if( tableExists() ) return true; // database already exists QSqlQuery data(db_); return data.exec("CREATE TABLE properties (" " id INT(10) PRIMARY KEY AUTO_INCREMENT," " variable VARCHAR(150)," " network VARCHAR(50)," // enforced limit in config.cpp " receiver VARCHAR(50)," // usually, max = 9 or 30 " sender VARCHAR(50)," // usually, max = 9 or 30 " value TEXT" ");"); } bool Database::tableExists() const { return db_.record("properties").count() > 0; } QString Database::typeToQtPlugin(const QString &type) { if( type.toLower() == "sqlite" ) return "QSQLITE"; if( type.toLower() == "mysql" ) return "QMYSQL"; qWarning() << "typeToQtPlugin: Unknown type: " << type; return ""; } <|endoftext|>
<commit_before>/***************************************************************************** * intf_beos.cpp: beos interface ***************************************************************************** * Copyright (C) 1999, 2000, 2001 VideoLAN * $Id: Interface.cpp,v 1.13 2003/05/30 17:30:54 titer Exp $ * * Authors: Jean-Marc Dressler <[email protected]> * Samuel Hocevar <[email protected]> * Tony Castley <[email protected]> * Richard Shepherd <[email protected]> * Stephan Aßmus <[email protected]> * Eric Petit <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <stdio.h> #include <stdlib.h> /* malloc(), free() */ #include <InterfaceKit.h> #include <Application.h> #include <Message.h> #include <string.h> #include <vlc/vlc.h> #include <vlc/intf.h> #include <vlc/aout.h> #include <aout_internal.h> #include "VlcWrapper.h" #include "InterfaceWindow.h" #include "MsgVals.h" /***************************************************************************** * Local prototype *****************************************************************************/ static void Run ( intf_thread_t *p_intf ); /***************************************************************************** * intf_Open: initialize interface *****************************************************************************/ int E_(OpenIntf) ( vlc_object_t *p_this ) { intf_thread_t * p_intf = (intf_thread_t*) p_this; /* Allocate instance and initialize some members */ p_intf->p_sys = (intf_sys_t*) malloc( sizeof( intf_sys_t ) ); if( p_intf->p_sys == NULL ) { msg_Err( p_intf, "out of memory" ); return( 1 ); } p_intf->p_sys->p_sub = msg_Subscribe( p_intf ); p_intf->p_sys->p_wrapper = new VlcWrapper( p_intf ); p_intf->pf_run = Run; /* Create the interface window */ BScreen screen(B_MAIN_SCREEN_ID); BRect rect = screen.Frame(); rect.top = rect.bottom-100; rect.bottom -= 50; rect.left += 50; rect.right = rect.left + 350; p_intf->p_sys->p_window = new InterfaceWindow( rect, "VLC " PACKAGE_VERSION, p_intf ); if( p_intf->p_sys->p_window == 0 ) { free( p_intf->p_sys ); msg_Err( p_intf, "cannot allocate InterfaceWindow" ); return( 1 ); } else { /* Make the be_app aware the interface has been created */ BMessage message(INTERFACE_CREATED); message.AddPointer("window", p_intf->p_sys->p_window); be_app->PostMessage(&message); } p_intf->p_sys->i_saved_volume = AOUT_VOLUME_DEFAULT; p_intf->p_sys->b_loop = 0; p_intf->p_sys->b_mute = 0; return( 0 ); } /***************************************************************************** * intf_Close: destroy dummy interface *****************************************************************************/ void E_(CloseIntf) ( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t*) p_this; msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub ); /* Destroy the interface window */ p_intf->p_sys->p_window->Lock(); p_intf->p_sys->p_window->Quit(); /* Destroy structure */ delete p_intf->p_sys->p_wrapper; free( p_intf->p_sys ); } /***************************************************************************** * intf_Run: event loop *****************************************************************************/ static void Run( intf_thread_t *p_intf ) { while( !p_intf->b_die ) { /* Update VlcWrapper internals (p_input, etc) */ p_intf->p_sys->p_wrapper->UpdateInput(); /* Manage the slider */ p_intf->p_sys->p_window->UpdateInterface(); /* Wait a bit */ msleep( INTF_IDLE_SLEEP ); } } <commit_msg> modules/gui/beos/Interface.cpp : fixed a possible crash<commit_after>/***************************************************************************** * intf_beos.cpp: beos interface ***************************************************************************** * Copyright (C) 1999, 2000, 2001 VideoLAN * $Id: Interface.cpp,v 1.14 2003/06/13 00:15:40 titer Exp $ * * Authors: Jean-Marc Dressler <[email protected]> * Samuel Hocevar <[email protected]> * Tony Castley <[email protected]> * Richard Shepherd <[email protected]> * Stephan Aßmus <[email protected]> * Eric Petit <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <stdio.h> #include <stdlib.h> /* malloc(), free() */ #include <InterfaceKit.h> #include <Application.h> #include <Message.h> #include <string.h> #include <vlc/vlc.h> #include <vlc/intf.h> #include <vlc/aout.h> #include <aout_internal.h> #include "VlcWrapper.h" #include "InterfaceWindow.h" #include "MsgVals.h" /***************************************************************************** * Local prototype *****************************************************************************/ static void Run ( intf_thread_t *p_intf ); /***************************************************************************** * intf_Open: initialize interface *****************************************************************************/ int E_(OpenIntf) ( vlc_object_t *p_this ) { intf_thread_t * p_intf = (intf_thread_t*) p_this; /* Allocate instance and initialize some members */ p_intf->p_sys = (intf_sys_t*) malloc( sizeof( intf_sys_t ) ); if( p_intf->p_sys == NULL ) { msg_Err( p_intf, "out of memory" ); return( 1 ); } p_intf->p_sys->p_sub = msg_Subscribe( p_intf ); p_intf->p_sys->p_wrapper = new VlcWrapper( p_intf ); p_intf->pf_run = Run; /* Create the interface window */ BScreen screen(B_MAIN_SCREEN_ID); BRect rect = screen.Frame(); rect.top = rect.bottom-100; rect.bottom -= 50; rect.left += 50; rect.right = rect.left + 350; p_intf->p_sys->p_window = new InterfaceWindow( rect, "VLC " PACKAGE_VERSION, p_intf ); if( p_intf->p_sys->p_window == 0 ) { free( p_intf->p_sys ); msg_Err( p_intf, "cannot allocate InterfaceWindow" ); return( 1 ); } else { /* Make the be_app aware the interface has been created */ BMessage message(INTERFACE_CREATED); message.AddPointer("window", p_intf->p_sys->p_window); be_app->PostMessage(&message); } p_intf->p_sys->i_saved_volume = AOUT_VOLUME_DEFAULT; p_intf->p_sys->b_loop = 0; p_intf->p_sys->b_mute = 0; return( 0 ); } /***************************************************************************** * intf_Close: destroy dummy interface *****************************************************************************/ void E_(CloseIntf) ( vlc_object_t *p_this ) { intf_thread_t *p_intf = (intf_thread_t*) p_this; msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub ); /* Destroy the interface window */ if( p_intf->p_sys->p_window->Lock() ) p_intf->p_sys->p_window->Quit(); /* Destroy structure */ delete p_intf->p_sys->p_wrapper; free( p_intf->p_sys ); } /***************************************************************************** * intf_Run: event loop *****************************************************************************/ static void Run( intf_thread_t *p_intf ) { while( !p_intf->b_die ) { /* Update VlcWrapper internals (p_input, etc) */ p_intf->p_sys->p_wrapper->UpdateInput(); /* Manage the slider */ p_intf->p_sys->p_window->UpdateInterface(); /* Wait a bit */ msleep( INTF_IDLE_SLEEP ); } } <|endoftext|>
<commit_before>#include <QDebug> #include "Utils/QRunTimeError.hpp" #include "Crypto/CryptoFactory.hpp" #include "ShuffleBlamer.hpp" using Dissent::Utils::QRunTimeError; using Dissent::Crypto::CryptoFactory; using Dissent::Crypto::OnionEncryptor; namespace Dissent { namespace Anonymity { ShuffleBlamer::ShuffleBlamer(const Group &group, const Id &round_id, const QVector<Log> &logs, const QVector<QSharedPointer<AsymmetricKey> > &private_keys) : _group(group), _shufflers(group.GetSubgroup()), _logs(logs), _private_keys(private_keys), _bad_nodes(_group.Count(), false), _reasons(_group.Count()), _set(false) { for(int idx = 0; idx < _group.Count(); idx++) { QSharedPointer<AsymmetricKey> key; int sidx = _shufflers.GetIndex(_group.GetId(idx)); if(sidx >= 0) { key = _private_keys[sidx]; } _rounds.append(new ShuffleRoundBlame(_group, _group.GetId(idx), round_id, key)); } } ShuffleBlamer::~ShuffleBlamer() { foreach(Round *round, _rounds) { delete round; } } void ShuffleBlamer::Set(const Id &id, const QString &reason) { Set(_group.GetIndex(id), reason); } void ShuffleBlamer::Set(int idx, const QString &reason) { qDebug() << "Blame:" << idx << ":" << reason; _bad_nodes[idx] = true; _reasons[idx].append(reason); _set = true; } void ShuffleBlamer::Start() { qDebug() << "Blame: Parsing logs"; ParseLogs(); qDebug() << "Blame: Checking public keys"; CheckPublicKeys(); if(!_set) { qDebug() << "Blame: Checking shuffle / data"; CheckShuffle(); } if(!_set) { qDebug() << "Blame: Checking go / no go"; CheckVerification(); } qDebug() << "Blame: Done"; } const QVector<QString> &ShuffleBlamer::GetReasons(int idx) { return _reasons[idx]; } void ShuffleBlamer::ParseLogs() { for(int idx = 0; idx < _logs.count(); idx++) { ParseLog(idx); } } void ShuffleBlamer::ParseLog(int idx) { Log &clog = _logs[idx]; ShuffleRoundBlame *round = _rounds[idx]; round->Start(); for(int jdx = 0; jdx < clog.Count(); jdx++) { QPair<QByteArray, Id> entry = clog.At(jdx); try { round->ProcessData(entry.second, entry.first); } catch (QRunTimeError &err) { qWarning() << idx << "received a message from" << _group.GetIndex(entry.second) << "in state" << ShuffleRound::StateToString(round->GetState()) << "causing the following exception: " << err.What(); Set(idx, err.What()); } } } void ShuffleBlamer::CheckPublicKeys() { // First fine the first good peer and also mark all the bad peers int first_good = -1; for(int idx = 0; idx < _rounds.count(); idx++) { if(_rounds[idx]->GetState() == ShuffleRound::KeySharing) { Set(idx, "Missing key log entries"); } if(first_good == -1) { first_good = idx; } } QVector<QSharedPointer<AsymmetricKey> > inner_keys = _rounds[first_good]->GetPublicInnerKeys(); QVector<QSharedPointer<AsymmetricKey> > outer_keys = _rounds[first_good]->GetPublicOuterKeys(); if(inner_keys.count() != outer_keys.count()) { qCritical() << "Key sizes don't match"; } for(int idx = 0; idx < _shufflers.Count(); idx++) { if(idx == first_good) { continue; } if(_rounds[idx]->GetState() == ShuffleRound::KeySharing) { continue; } int sidx = _shufflers.GetIndex(_group.GetId(idx)); if(sidx >= 0) { QSharedPointer<AsymmetricKey> p_outer_key = _rounds[idx]->GetPrivateOuterKey(); if(!p_outer_key->IsValid()) { Set(idx, "Invalid private key"); continue; } int kdx = _rounds[0]->CalculateKidx(sidx); if(!p_outer_key->VerifyKey(*(outer_keys[kdx]))) { Set(idx, "Mismatched private key"); } } QVector<QSharedPointer<AsymmetricKey> > cinner_keys = _rounds[idx]->GetPublicInnerKeys(); QVector<QSharedPointer<AsymmetricKey> > couter_keys = _rounds[idx]->GetPublicOuterKeys(); if(inner_keys.count() != cinner_keys.count() || outer_keys.count() != couter_keys.count()) { qCritical() << "Peers keys count don't match"; } for(int jdx = 0; jdx < cinner_keys.count(); jdx++) { // Note public keys are kept in reverse order... int kdx = _rounds[0]->CalculateKidx(jdx); // If a node has passed KeySharing, then all messasges are validated and // any "suprise" keys were introduced by the provider of the key if(*(inner_keys[kdx]) == *(cinner_keys[kdx]) && *(outer_keys[kdx]) == *(couter_keys[kdx])) { continue; } Set(jdx, "Bad public keys"); } } } void ShuffleBlamer::CheckShuffle() { int last_shuffle = -1; bool verified = false; for(int idx = 0; idx < _shufflers.Count() && !verified; idx++) { int gidx = _group.GetIndex(_shufflers.GetId(idx)); ShuffleRound::State cstate = _rounds[gidx]->GetState(); switch(cstate) { case ShuffleRound::Offline: case ShuffleRound::KeySharing: case ShuffleRound::DataSubmission: case ShuffleRound::WaitingForShuffle: break; case ShuffleRound::WaitingForEncryptedInnerData: case ShuffleRound::Shuffling: last_shuffle = idx; break; case ShuffleRound::Verification: last_shuffle = _shufflers.Count() - 1; verified = true; break; default: break; } } // First node misbehaved ... if(last_shuffle == -1) { Set(0, "Never got shuffle data..."); } // Verify all nodes are in their proper state... for(int idx = 0; idx <= last_shuffle; idx++) { int gidx = _group.GetIndex(_shufflers.GetId(idx)); ShuffleRound::State cstate = _rounds[gidx]->GetState(); switch(cstate) { case ShuffleRound::WaitingForEncryptedInnerData: case ShuffleRound::Verification: continue; default: break; } Set(idx, "Another wrong state..."); } // If any failures ... let's not try to deal with the logic at this point... if(_set) { return; } _inner_data = _rounds[_group.GetIndex(_shufflers.GetId(0))]->GetShuffleCipherText(); OnionEncryptor *oe = CryptoFactory::GetInstance().GetOnionEncryptor(); for(int idx = 0; idx < _private_keys.count(); idx++) { QVector<QByteArray> outdata; QVector<int> bad; oe->Decrypt(_private_keys[idx], _inner_data, outdata, &bad); _inner_data = outdata; if(bad.count() == 0) { continue; } foreach(int bidx, bad) { Set(bidx, "Invalid crypto data"); } } // Check intermediary steps for(int idx = 0; idx < last_shuffle; idx++) { int pidx = _group.GetIndex(_shufflers.GetId(idx)); int nidx = _group.GetIndex(_shufflers.GetId(idx + 1)); const QVector<QByteArray> outdata = _rounds[pidx]->GetShuffleClearText(); const QVector<QByteArray> indata = _rounds[nidx]->GetShuffleCipherText(); if(CountMatches(outdata, indata) != _rounds.count()) { qDebug() << "Checking" << pidx << "output against" << nidx << "input: fail"; Set(pidx, "Changed data"); return; } qDebug() << "Checking" << pidx << "output against" << nidx << "input: success"; } if(last_shuffle != _group.GetIndex(_shufflers.GetId(_shufflers.Count() - 1))) { return; } // Check final step const QVector<QByteArray> outdata = _rounds[last_shuffle]->GetShuffleClearText(); if(outdata.isEmpty()) { Set(last_shuffle, "No final data"); return; } if(CountMatches(outdata, _inner_data) != _rounds.count()) { Set(last_shuffle, "Changed final data"); return; } for(int idx = 0; idx < _rounds.count(); idx++) { const QVector<QByteArray> indata = _rounds[idx]->GetEncryptedData(); if(indata.count() == 0) { continue; } if(CountMatches(outdata, indata) != _rounds.count()) { Set(last_shuffle, "Changed final data"); return; } } } int ShuffleBlamer::CountMatches(const QVector<QByteArray> &lhs, const QVector<QByteArray> &rhs) { int matches = 0; foreach(const QByteArray &data, lhs) { if(rhs.contains(data)) { matches++; } } return matches; } void ShuffleBlamer::CheckVerification() { QBitArray go(_rounds.count(), false); QBitArray go_found(_rounds.count(), false); for(int idx = 0; idx < _rounds.count(); idx++) { ShuffleRoundBlame *psrb = _rounds[idx]; for(int jdx = 0; jdx < _rounds.count(); jdx++) { int go_val = psrb->GetGo(jdx); if(go_val == 0) { continue; } else if(go_found[jdx]) { if((go[jdx] && (go_val == 1)) || (!go[jdx] && (go_val == -1))) { continue; } Set(jdx, "Different go states different nodes"); } else { go[jdx] = go_val == 1 ? true : false; go_found[jdx] = true; } } } int first = _group.GetIndex(_shufflers.GetId(0)); QVector<QByteArray> ciphertext = _rounds[first]->GetShuffleCipherText(); int last = _group.GetIndex(_shufflers.GetId(_shufflers.Count() - 1)); QVector<QByteArray> cleartext = _rounds[last]->GetShuffleClearText(); for(int idx = 0; idx < _rounds.count(); idx++) { bool good = cleartext.contains(_inner_data[idx]); if(!go_found[idx] || (!good && !go[idx]) || (good && go[idx])) { continue; } Set(idx, "Bad go"); } } } } <commit_msg>[Anonymity] Seems like a corner case where bad things can happen<commit_after>#include <QDebug> #include "Utils/QRunTimeError.hpp" #include "Crypto/CryptoFactory.hpp" #include "ShuffleBlamer.hpp" using Dissent::Utils::QRunTimeError; using Dissent::Crypto::CryptoFactory; using Dissent::Crypto::OnionEncryptor; namespace Dissent { namespace Anonymity { ShuffleBlamer::ShuffleBlamer(const Group &group, const Id &round_id, const QVector<Log> &logs, const QVector<QSharedPointer<AsymmetricKey> > &private_keys) : _group(group), _shufflers(group.GetSubgroup()), _logs(logs), _private_keys(private_keys), _bad_nodes(_group.Count(), false), _reasons(_group.Count()), _set(false) { for(int idx = 0; idx < _group.Count(); idx++) { QSharedPointer<AsymmetricKey> key; int sidx = _shufflers.GetIndex(_group.GetId(idx)); if(sidx >= 0) { key = _private_keys[sidx]; } _rounds.append(new ShuffleRoundBlame(_group, _group.GetId(idx), round_id, key)); } } ShuffleBlamer::~ShuffleBlamer() { foreach(Round *round, _rounds) { delete round; } } void ShuffleBlamer::Set(const Id &id, const QString &reason) { Set(_group.GetIndex(id), reason); } void ShuffleBlamer::Set(int idx, const QString &reason) { qDebug() << "Blame:" << idx << ":" << reason; _bad_nodes[idx] = true; _reasons[idx].append(reason); _set = true; } void ShuffleBlamer::Start() { qDebug() << "Blame: Parsing logs"; ParseLogs(); qDebug() << "Blame: Checking public keys"; CheckPublicKeys(); if(!_set) { qDebug() << "Blame: Checking shuffle / data"; CheckShuffle(); } if(!_set) { qDebug() << "Blame: Checking go / no go"; CheckVerification(); } qDebug() << "Blame: Done"; } const QVector<QString> &ShuffleBlamer::GetReasons(int idx) { return _reasons[idx]; } void ShuffleBlamer::ParseLogs() { for(int idx = 0; idx < _logs.count(); idx++) { ParseLog(idx); } } void ShuffleBlamer::ParseLog(int idx) { Log &clog = _logs[idx]; ShuffleRoundBlame *round = _rounds[idx]; round->Start(); for(int jdx = 0; jdx < clog.Count(); jdx++) { QPair<QByteArray, Id> entry = clog.At(jdx); try { round->ProcessData(entry.second, entry.first); } catch (QRunTimeError &err) { qWarning() << idx << "received a message from" << _group.GetIndex(entry.second) << "in state" << ShuffleRound::StateToString(round->GetState()) << "causing the following exception: " << err.What(); Set(idx, err.What()); } } } void ShuffleBlamer::CheckPublicKeys() { // First fine the first good peer and also mark all the bad peers int first_good = -1; for(int idx = 0; idx < _rounds.count(); idx++) { if(_rounds[idx]->GetState() == ShuffleRound::KeySharing) { Set(idx, "Missing key log entries"); } if(first_good == -1) { first_good = idx; } } QVector<QSharedPointer<AsymmetricKey> > inner_keys = _rounds[first_good]->GetPublicInnerKeys(); QVector<QSharedPointer<AsymmetricKey> > outer_keys = _rounds[first_good]->GetPublicOuterKeys(); if(inner_keys.count() != outer_keys.count()) { qCritical() << "Key sizes don't match"; } for(int idx = 0; idx < _shufflers.Count(); idx++) { if(idx == first_good) { continue; } if(_rounds[idx]->GetState() == ShuffleRound::KeySharing) { continue; } int sidx = _shufflers.GetIndex(_group.GetId(idx)); if(sidx >= 0) { QSharedPointer<AsymmetricKey> p_outer_key = _rounds[idx]->GetPrivateOuterKey(); if(!p_outer_key->IsValid()) { Set(idx, "Invalid private key"); continue; } int kdx = _rounds[0]->CalculateKidx(sidx); if(!p_outer_key->VerifyKey(*(outer_keys[kdx]))) { Set(idx, "Mismatched private key"); } } QVector<QSharedPointer<AsymmetricKey> > cinner_keys = _rounds[idx]->GetPublicInnerKeys(); QVector<QSharedPointer<AsymmetricKey> > couter_keys = _rounds[idx]->GetPublicOuterKeys(); if(inner_keys.count() != cinner_keys.count() || outer_keys.count() != couter_keys.count()) { qCritical() << "Peers keys count don't match"; } for(int jdx = 0; jdx < cinner_keys.count(); jdx++) { // Note public keys are kept in reverse order... int kdx = _rounds[0]->CalculateKidx(jdx); // If a node has passed KeySharing, then all messasges are validated and // any "suprise" keys were introduced by the provider of the key if(*(inner_keys[kdx]) == *(cinner_keys[kdx]) && *(outer_keys[kdx]) == *(couter_keys[kdx])) { continue; } Set(jdx, "Bad public keys"); } } } void ShuffleBlamer::CheckShuffle() { int last_shuffle = -1; bool verified = false; for(int idx = 0; idx < _shufflers.Count() && !verified; idx++) { int gidx = _group.GetIndex(_shufflers.GetId(idx)); ShuffleRound::State cstate = _rounds[gidx]->GetState(); switch(cstate) { case ShuffleRound::Offline: case ShuffleRound::KeySharing: case ShuffleRound::DataSubmission: case ShuffleRound::WaitingForShuffle: break; case ShuffleRound::WaitingForEncryptedInnerData: case ShuffleRound::Shuffling: last_shuffle = idx; break; case ShuffleRound::Verification: last_shuffle = _shufflers.Count() - 1; verified = true; break; default: break; } } // First node misbehaved ... if(last_shuffle == -1) { Set(0, "Never got shuffle data..."); } // Verify all nodes are in their proper state... for(int idx = 0; idx <= last_shuffle; idx++) { int gidx = _group.GetIndex(_shufflers.GetId(idx)); ShuffleRound::State cstate = _rounds[gidx]->GetState(); switch(cstate) { case ShuffleRound::WaitingForEncryptedInnerData: case ShuffleRound::Verification: continue; default: break; } Set(idx, "Another wrong state..."); } // If any failures ... let's not try to deal with the logic at this point... if(_set) { return; } _inner_data = _rounds[_group.GetIndex(_shufflers.GetId(0))]->GetShuffleCipherText(); OnionEncryptor *oe = CryptoFactory::GetInstance().GetOnionEncryptor(); for(int idx = 0; idx < _private_keys.count(); idx++) { QVector<QByteArray> outdata; QVector<int> bad; oe->Decrypt(_private_keys[idx], _inner_data, outdata, &bad); _inner_data = outdata; if(bad.count() == 0) { continue; } foreach(int bidx, bad) { Set(bidx, "Invalid crypto data"); } } if(_set) { return; } // Check intermediary steps for(int idx = 0; idx < last_shuffle; idx++) { int pidx = _group.GetIndex(_shufflers.GetId(idx)); int nidx = _group.GetIndex(_shufflers.GetId(idx + 1)); const QVector<QByteArray> outdata = _rounds[pidx]->GetShuffleClearText(); const QVector<QByteArray> indata = _rounds[nidx]->GetShuffleCipherText(); if(CountMatches(outdata, indata) != _rounds.count()) { qDebug() << "Checking" << pidx << "output against" << nidx << "input: fail"; Set(pidx, "Changed data"); return; } qDebug() << "Checking" << pidx << "output against" << nidx << "input: success"; } if(last_shuffle != _group.GetIndex(_shufflers.GetId(_shufflers.Count() - 1))) { return; } // Check final step const QVector<QByteArray> outdata = _rounds[last_shuffle]->GetShuffleClearText(); if(outdata.isEmpty()) { Set(last_shuffle, "No final data"); return; } if(CountMatches(outdata, _inner_data) != _rounds.count()) { Set(last_shuffle, "Changed final data"); return; } for(int idx = 0; idx < _rounds.count(); idx++) { const QVector<QByteArray> indata = _rounds[idx]->GetEncryptedData(); if(indata.count() == 0) { continue; } if(CountMatches(outdata, indata) != _rounds.count()) { Set(last_shuffle, "Changed final data"); return; } } } int ShuffleBlamer::CountMatches(const QVector<QByteArray> &lhs, const QVector<QByteArray> &rhs) { int matches = 0; foreach(const QByteArray &data, lhs) { if(rhs.contains(data)) { matches++; } } return matches; } void ShuffleBlamer::CheckVerification() { QBitArray go(_rounds.count(), false); QBitArray go_found(_rounds.count(), false); for(int idx = 0; idx < _rounds.count(); idx++) { ShuffleRoundBlame *psrb = _rounds[idx]; for(int jdx = 0; jdx < _rounds.count(); jdx++) { int go_val = psrb->GetGo(jdx); if(go_val == 0) { continue; } else if(go_found[jdx]) { if((go[jdx] && (go_val == 1)) || (!go[jdx] && (go_val == -1))) { continue; } Set(jdx, "Different go states different nodes"); } else { go[jdx] = go_val == 1 ? true : false; go_found[jdx] = true; } } } int first = _group.GetIndex(_shufflers.GetId(0)); QVector<QByteArray> ciphertext = _rounds[first]->GetShuffleCipherText(); int last = _group.GetIndex(_shufflers.GetId(_shufflers.Count() - 1)); QVector<QByteArray> cleartext = _rounds[last]->GetShuffleClearText(); for(int idx = 0; idx < _rounds.count(); idx++) { bool good = cleartext.contains(_inner_data[idx]); if(!go_found[idx] || (!good && !go[idx]) || (good && go[idx])) { continue; } Set(idx, "Bad go"); } } } } <|endoftext|>
<commit_before>// // geometry.cpp // GLAMER // // Created by bmetcalf on 7/24/14. // // #include "geometry.h" #include "Tree.h" #include "point.h" /// output cartisian coordinates of the point void Utilities::Geometry::SphericalPoint::sphericalTOcartisian(PosType x[]) const{ x[0] = r*cos(theta)*cos(phi); x[1] = r*cos(theta)*sin(phi); x[2] = r*sin(theta); } /// set the spherical coordinates of the point from the cartisian coordinates void Utilities::Geometry::SphericalPoint::cartisianTOspherical(PosType const x[]){ r = sqrt( x[0]*x[0] + x[1]*x[1] +x[2]*x[2]); theta = asin(x[2]/r); phi = atan2(x[1],x[0]); } /** \brief Calculates the stereographic projection of the point onto a plane. * * The result is in radian units. Near the central point this is a rectolinear projection * onto a tangent plane. */ void Utilities::Geometry::SphericalPoint::StereographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType x[] /// 2D output coordinate on projection ) const{ PosType k = 2/( 1 + sin(central.theta)*sin(theta) + cos(central.theta)*cos(theta)*cos(phi - central.phi) ); x[0] = k*(cos(theta)*sin(phi - central.phi)); x[1] = k*(cos(central.theta)*sin(theta) - sin(central.theta)*cos(theta)*cos(phi - central.phi)); } /** \brief Calculates the orthographic projection of the point onto a plane. * * The result is in radian units. Near the central point this is a rectolinear projection * onto a tangent plane. */ void Utilities::Geometry::SphericalPoint::OrthographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType x[] /// 2D output coordinate on projection ) const{ x[0] = cos(theta)*sin(phi - central.phi); x[1] = cos(central.theta)*sin(theta) - sin(central.theta)*cos(theta)*cos(phi - central.phi); } /** \brief Convert from an orthographic projection of the plane onto the unit sphere */ void Utilities::Geometry::SphericalPoint::InverseOrthographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType const x[] /// 2D output coordinate on projection ){ PosType rho = sqrt(x[0]*x[0] + x[1]*x[1]); PosType c = asin(rho); r=1.0; theta = asin( cos(c)*sin(central.theta) + x[1]*sin(c)*cos(central.theta)/rho ); phi = central.phi + atan2(x[0]*sin(c),rho*cos(central.theta)*cos(c) - x[1]*sin(central.theta)*sin(c) ); } /// 3 dimensional distance between points PosType Utilities::Geometry::Seporation(const SphericalPoint &p1,const SphericalPoint &p2){ PosType x1[3],x2[3]; p1.sphericalTOcartisian(x1); p2.sphericalTOcartisian(x2); return sqrt( (x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]) + (x1[2]-x2[2])*(x1[2]-x2[2]) ); } /// Angular seporation between points PosType Utilities::Geometry::AngleSeporation(const SphericalPoint &p1,const SphericalPoint &p2){ return acos(sin(p1.theta)*sin(p2.theta) + cos(p1.theta)*cos(p2.theta)*cos(p1.phi-p2.phi)); } bool Utilities::Geometry::intersect(const PosType a1[],const PosType a2[],const PosType b1[],const PosType b2[]){ if(a1 == b1 || a1 == b2) return false; if(a2 == b1 || a2 == b2) return false; int o1 = Utilities::Geometry::orientation(a1, a2, b1); int o2 = Utilities::Geometry::orientation(a1, a2, b2); int o3 = Utilities::Geometry::orientation(b1, b2, a1); int o4 = Utilities::Geometry::orientation(b1, b2, a2); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && Utilities::Geometry::onSegment(a1, b1, a2)) return true; // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && Utilities::Geometry::onSegment(a1, b2, a2)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && Utilities::Geometry::onSegment(b1, a1, b2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && Utilities::Geometry::onSegment(b1, a2, b2)) return true; return false; // Doesn't fall in any of the above cases } int Utilities::Geometry::intersect(const std::vector<Point_2d> &curve){ if(curve.size() < 4) return 0; int intersections = 0; for(size_t i=0;i<curve.size()-2;++i){ for(size_t j=i+2;j<curve.size()-1;++j){ intersections += Utilities::Geometry::intersect(curve[i].x,curve[i+1].x,curve[j].x,curve[j+1].x); } intersections += Utilities::Geometry::intersect(curve[i].x,curve[i+1].x ,curve.back().x,curve[0].x); } return intersections; } int Utilities::Geometry::orientation(const PosType p[],const PosType q[],const PosType r[]) { // See 10th slides from following link for derivation of the formula double val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); if (val == 0.0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } /** \brief Given three colinear points p, q, r, the function checks if point q lies on line segment 'pr', but not at p or r */ bool Utilities::Geometry::onSegment(const PosType p[], const PosType q[], const PosType r[]) { if (q[0] < MAX(p[0], r[0]) && q[0] > MIN(p[0], r[0]) && q[1] < MAX(p[1], r[1]) && q[1] > MIN(p[1], r[1])) return true; return false; } double Utilities::Geometry::AngleBetween2d(double v1[],double v2[]){ double y = (v1[0] * v2[1]) - (v2[0] * v1[1]); double x = (v1[0] * v2[0]) + (v1[1] * v2[1]); if(y == 0 && x < 0 ) return pi; return atan2(y, x); } int Utilities::Geometry::incurve(PosType x[],std::vector<double *> curve){ int number = 0; size_t i; Point point; for(i=0;i<curve.size()-1;++i){ if( (x[1] >= curve[i][1])*(x[1] <= curve[i+1][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[i+1]) <= 1) ++number; }else if( (x[1] <= curve[i][1])*(x[1] > curve[i+1][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[i+1]) == 2) --number; } } if( (x[1] >= curve[i][1])*(x[1] <= curve[0][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[0]) <= 1) ++number; }else if( (x[1] <= curve[i][1])*(x[1] > curve[0][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[0]) == 2) --number; } return number == 0 ? 0 : 1; } std::ostream &operator<<(std::ostream &os, Utilities::Geometry::SphericalPoint const &p){ return os << p.r << " " << p.theta << " " << p.phi; } <commit_msg>Change to std::ostream &operator<<(std::ostream &os, Utilities::Geometry::SphericalPoint const &p)<commit_after>// // geometry.cpp // GLAMER // // Created by bmetcalf on 7/24/14. // // #include "geometry.h" #include "Tree.h" #include "point.h" /// output cartisian coordinates of the point void Utilities::Geometry::SphericalPoint::sphericalTOcartisian(PosType x[]) const{ x[0] = r*cos(theta)*cos(phi); x[1] = r*cos(theta)*sin(phi); x[2] = r*sin(theta); } /// set the spherical coordinates of the point from the cartisian coordinates void Utilities::Geometry::SphericalPoint::cartisianTOspherical(PosType const x[]){ r = sqrt( x[0]*x[0] + x[1]*x[1] +x[2]*x[2]); theta = asin(x[2]/r); phi = atan2(x[1],x[0]); } /** \brief Calculates the stereographic projection of the point onto a plane. * * The result is in radian units. Near the central point this is a rectolinear projection * onto a tangent plane. */ void Utilities::Geometry::SphericalPoint::StereographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType x[] /// 2D output coordinate on projection ) const{ PosType k = 2/( 1 + sin(central.theta)*sin(theta) + cos(central.theta)*cos(theta)*cos(phi - central.phi) ); x[0] = k*(cos(theta)*sin(phi - central.phi)); x[1] = k*(cos(central.theta)*sin(theta) - sin(central.theta)*cos(theta)*cos(phi - central.phi)); } /** \brief Calculates the orthographic projection of the point onto a plane. * * The result is in radian units. Near the central point this is a rectolinear projection * onto a tangent plane. */ void Utilities::Geometry::SphericalPoint::OrthographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType x[] /// 2D output coordinate on projection ) const{ x[0] = cos(theta)*sin(phi - central.phi); x[1] = cos(central.theta)*sin(theta) - sin(central.theta)*cos(theta)*cos(phi - central.phi); } /** \brief Convert from an orthographic projection of the plane onto the unit sphere */ void Utilities::Geometry::SphericalPoint::InverseOrthographicProjection( const SphericalPoint &central /// point on the sphere where the tangent plane touches ,PosType const x[] /// 2D output coordinate on projection ){ PosType rho = sqrt(x[0]*x[0] + x[1]*x[1]); PosType c = asin(rho); r=1.0; theta = asin( cos(c)*sin(central.theta) + x[1]*sin(c)*cos(central.theta)/rho ); phi = central.phi + atan2(x[0]*sin(c),rho*cos(central.theta)*cos(c) - x[1]*sin(central.theta)*sin(c) ); } /// 3 dimensional distance between points PosType Utilities::Geometry::Seporation(const SphericalPoint &p1,const SphericalPoint &p2){ PosType x1[3],x2[3]; p1.sphericalTOcartisian(x1); p2.sphericalTOcartisian(x2); return sqrt( (x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]) + (x1[2]-x2[2])*(x1[2]-x2[2]) ); } /// Angular seporation between points PosType Utilities::Geometry::AngleSeporation(const SphericalPoint &p1,const SphericalPoint &p2){ return acos(sin(p1.theta)*sin(p2.theta) + cos(p1.theta)*cos(p2.theta)*cos(p1.phi-p2.phi)); } bool Utilities::Geometry::intersect(const PosType a1[],const PosType a2[],const PosType b1[],const PosType b2[]){ if(a1 == b1 || a1 == b2) return false; if(a2 == b1 || a2 == b2) return false; int o1 = Utilities::Geometry::orientation(a1, a2, b1); int o2 = Utilities::Geometry::orientation(a1, a2, b2); int o3 = Utilities::Geometry::orientation(b1, b2, a1); int o4 = Utilities::Geometry::orientation(b1, b2, a2); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are colinear and p2 lies on segment p1q1 if (o1 == 0 && Utilities::Geometry::onSegment(a1, b1, a2)) return true; // p1, q1 and p2 are colinear and q2 lies on segment p1q1 if (o2 == 0 && Utilities::Geometry::onSegment(a1, b2, a2)) return true; // p2, q2 and p1 are colinear and p1 lies on segment p2q2 if (o3 == 0 && Utilities::Geometry::onSegment(b1, a1, b2)) return true; // p2, q2 and q1 are colinear and q1 lies on segment p2q2 if (o4 == 0 && Utilities::Geometry::onSegment(b1, a2, b2)) return true; return false; // Doesn't fall in any of the above cases } int Utilities::Geometry::intersect(const std::vector<Point_2d> &curve){ if(curve.size() < 4) return 0; int intersections = 0; for(size_t i=0;i<curve.size()-2;++i){ for(size_t j=i+2;j<curve.size()-1;++j){ intersections += Utilities::Geometry::intersect(curve[i].x,curve[i+1].x,curve[j].x,curve[j+1].x); } intersections += Utilities::Geometry::intersect(curve[i].x,curve[i+1].x ,curve.back().x,curve[0].x); } return intersections; } int Utilities::Geometry::orientation(const PosType p[],const PosType q[],const PosType r[]) { // See 10th slides from following link for derivation of the formula double val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]); if (val == 0.0) return 0; // colinear return (val > 0)? 1: 2; // clock or counterclock wise } /** \brief Given three colinear points p, q, r, the function checks if point q lies on line segment 'pr', but not at p or r */ bool Utilities::Geometry::onSegment(const PosType p[], const PosType q[], const PosType r[]) { if (q[0] < MAX(p[0], r[0]) && q[0] > MIN(p[0], r[0]) && q[1] < MAX(p[1], r[1]) && q[1] > MIN(p[1], r[1])) return true; return false; } double Utilities::Geometry::AngleBetween2d(double v1[],double v2[]){ double y = (v1[0] * v2[1]) - (v2[0] * v1[1]); double x = (v1[0] * v2[0]) + (v1[1] * v2[1]); if(y == 0 && x < 0 ) return pi; return atan2(y, x); } int Utilities::Geometry::incurve(PosType x[],std::vector<double *> curve){ int number = 0; size_t i; Point point; for(i=0;i<curve.size()-1;++i){ if( (x[1] >= curve[i][1])*(x[1] <= curve[i+1][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[i+1]) <= 1) ++number; }else if( (x[1] <= curve[i][1])*(x[1] > curve[i+1][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[i+1]) == 2) --number; } } if( (x[1] >= curve[i][1])*(x[1] <= curve[0][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[0]) <= 1) ++number; }else if( (x[1] <= curve[i][1])*(x[1] > curve[0][1]) ){ if(Utilities::Geometry::orientation(curve[i], x, curve[0]) == 2) --number; } return number == 0 ? 0 : 1; } std::ostream &operator<<(std::ostream &os, Utilities::Geometry::SphericalPoint const &p){ return os << "r: " << p.r << " theta: " << p.theta << " phi: " << p.phi; } <|endoftext|>
<commit_before>#include "ResourceList.hpp" #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Geometry/StaticModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Hymn.hpp> #include <Engine/Entity/World.hpp> #include <Engine/Entity/Entity.hpp> #include <imgui.h> using namespace GUI; void ResourceList::Show() { ImGui::Begin("Resources"); // Entities. if (ImGui::TreeNode("Entities")) { if (ImGui::Button("Add entity")) Hymn().world.CreateEntity("Entity #" + std::to_string(Hymn().entityNumber++)); for (Entity* entity : Hymn().world.GetEntities()) { if (ImGui::Selectable(entity->name.c_str())) { entityEditors[entity].SetVisible(true); entityEditors[entity].SetEntity(entity); } if (ImGui::BeginPopupContextItem(entity->name.c_str())) { if (ImGui::Selectable("Delete")) { entity->Kill(); } ImGui::EndPopup(); } } ImGui::TreePop(); } // Entity editors. for (Entity* entity : Hymn().world.GetEntities()) { if (entityEditors[entity].IsVisible()) { entityEditors[entity].Show(); } } // Models. if (ImGui::TreeNode("Models")) { if (ImGui::Button("Add rigged model")) { Geometry::Model* model = new Geometry::RiggedModel(); model->name = "RiggedModel #" + std::to_string(Hymn().modelNumber++); Hymn().models.push_back(model); } if (ImGui::Button("Add static model")) { Geometry::Model* model = new Geometry::StaticModel(); model->name = "StaticModel #" + std::to_string(Hymn().modelNumber++); Hymn().models.push_back(model); } for (auto it = Hymn().models.begin(); it != Hymn().models.end(); ++it) { Geometry::Model* model = *it; if (ImGui::Selectable(model->name.c_str())) { modelEditors[model].SetVisible(true); modelEditors[model].SetModel(model); } if (ImGui::BeginPopupContextItem(model->name.c_str())) { if (ImGui::Selectable("Delete")) { delete model; Hymn().models.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Model editors. for (Geometry::Model* model : Hymn().models) { if (modelEditors[model].IsVisible()) { modelEditors[model].Show(); } } // Textures. if (ImGui::TreeNode("Textures")) { if (ImGui::Button("Add texture")) { Texture2D* texture = new Texture2D(); texture->name = "Texture #" + std::to_string(Hymn().textureNumber++); Hymn().textures.push_back(texture); } for (auto it = Hymn().textures.begin(); it != Hymn().textures.end(); ++it) { Texture2D* texture = *it; if (ImGui::Selectable(texture->name.c_str())) { textureEditors[texture].SetVisible(true); textureEditors[texture].SetTexture(texture); } if (ImGui::BeginPopupContextItem(texture->name.c_str())) { if (ImGui::Selectable("Delete")) { delete texture; Hymn().textures.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Texture editors. for (Texture2D* texture : Hymn().textures) { if (textureEditors[texture].IsVisible()) { textureEditors[texture].Show(); } } // Sounds. if (ImGui::TreeNode("Sounds")) { if (ImGui::Button("Add sound")) { Audio::SoundBuffer* sound = new Audio::SoundBuffer(); sound->name = "Sound #" + std::to_string(Hymn().soundNumber++); Hymn().sounds.push_back(sound); } for (auto it = Hymn().sounds.begin(); it != Hymn().sounds.end(); ++it) { Audio::SoundBuffer* sound = *it; if (ImGui::Selectable(sound->name.c_str())) { soundEditors[sound].SetVisible(true); soundEditors[sound].SetSound(sound); } if (ImGui::BeginPopupContextItem(sound->name.c_str())) { if (ImGui::Selectable("Delete")) { delete sound; Hymn().sounds.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Sound editors. for (Audio::SoundBuffer* sound : Hymn().sounds) { if (soundEditors[sound].IsVisible()) { soundEditors[sound].Show(); } } ImGui::End(); } bool ResourceList::IsVisible() const { return visible; } void ResourceList::SetVisible(bool visible) { this->visible = visible; } void ResourceList::HideEditors() { for (auto& editor : entityEditors) { editor.second.SetVisible(false); } for (auto& editor : modelEditors) { editor.second.SetVisible(false); } for (auto& editor : textureEditors) { editor.second.SetVisible(false); } for (auto& editor : soundEditors) { editor.second.SetVisible(false); } } <commit_msg>Show scenes in resource list<commit_after>#include "ResourceList.hpp" #include <Engine/Geometry/RiggedModel.hpp> #include <Engine/Geometry/StaticModel.hpp> #include <Engine/Texture/Texture2D.hpp> #include <Engine/Audio/SoundBuffer.hpp> #include <Engine/Hymn.hpp> #include <Engine/Entity/World.hpp> #include <Engine/Entity/Entity.hpp> #include <imgui.h> using namespace GUI; void ResourceList::Show() { ImGui::Begin("Resources"); // Scenes. if (ImGui::TreeNode("Scenes")) { if (ImGui::Button("Add scene")) Hymn().scenes.push_back("Scene #" + std::to_string(Hymn().scenes.size())); for (const std::string& scene : Hymn().scenes) { if (ImGui::Selectable(scene.c_str())) { /// @todo Scene editor. } if (ImGui::BeginPopupContextItem(scene.c_str())) { if (ImGui::Selectable("Delete")) { /// @todo Delete scene. } ImGui::EndPopup(); } } ImGui::TreePop(); } // Entities. if (ImGui::TreeNode("Entities")) { if (ImGui::Button("Add entity")) Hymn().world.CreateEntity("Entity #" + std::to_string(Hymn().entityNumber++)); for (Entity* entity : Hymn().world.GetEntities()) { if (ImGui::Selectable(entity->name.c_str())) { entityEditors[entity].SetVisible(true); entityEditors[entity].SetEntity(entity); } if (ImGui::BeginPopupContextItem(entity->name.c_str())) { if (ImGui::Selectable("Delete")) { entity->Kill(); } ImGui::EndPopup(); } } ImGui::TreePop(); } // Entity editors. for (Entity* entity : Hymn().world.GetEntities()) { if (entityEditors[entity].IsVisible()) { entityEditors[entity].Show(); } } // Models. if (ImGui::TreeNode("Models")) { if (ImGui::Button("Add rigged model")) { Geometry::Model* model = new Geometry::RiggedModel(); model->name = "RiggedModel #" + std::to_string(Hymn().modelNumber++); Hymn().models.push_back(model); } if (ImGui::Button("Add static model")) { Geometry::Model* model = new Geometry::StaticModel(); model->name = "StaticModel #" + std::to_string(Hymn().modelNumber++); Hymn().models.push_back(model); } for (auto it = Hymn().models.begin(); it != Hymn().models.end(); ++it) { Geometry::Model* model = *it; if (ImGui::Selectable(model->name.c_str())) { modelEditors[model].SetVisible(true); modelEditors[model].SetModel(model); } if (ImGui::BeginPopupContextItem(model->name.c_str())) { if (ImGui::Selectable("Delete")) { delete model; Hymn().models.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Model editors. for (Geometry::Model* model : Hymn().models) { if (modelEditors[model].IsVisible()) { modelEditors[model].Show(); } } // Textures. if (ImGui::TreeNode("Textures")) { if (ImGui::Button("Add texture")) { Texture2D* texture = new Texture2D(); texture->name = "Texture #" + std::to_string(Hymn().textureNumber++); Hymn().textures.push_back(texture); } for (auto it = Hymn().textures.begin(); it != Hymn().textures.end(); ++it) { Texture2D* texture = *it; if (ImGui::Selectable(texture->name.c_str())) { textureEditors[texture].SetVisible(true); textureEditors[texture].SetTexture(texture); } if (ImGui::BeginPopupContextItem(texture->name.c_str())) { if (ImGui::Selectable("Delete")) { delete texture; Hymn().textures.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Texture editors. for (Texture2D* texture : Hymn().textures) { if (textureEditors[texture].IsVisible()) { textureEditors[texture].Show(); } } // Sounds. if (ImGui::TreeNode("Sounds")) { if (ImGui::Button("Add sound")) { Audio::SoundBuffer* sound = new Audio::SoundBuffer(); sound->name = "Sound #" + std::to_string(Hymn().soundNumber++); Hymn().sounds.push_back(sound); } for (auto it = Hymn().sounds.begin(); it != Hymn().sounds.end(); ++it) { Audio::SoundBuffer* sound = *it; if (ImGui::Selectable(sound->name.c_str())) { soundEditors[sound].SetVisible(true); soundEditors[sound].SetSound(sound); } if (ImGui::BeginPopupContextItem(sound->name.c_str())) { if (ImGui::Selectable("Delete")) { delete sound; Hymn().sounds.erase(it); ImGui::EndPopup(); break; } ImGui::EndPopup(); } } ImGui::TreePop(); } // Sound editors. for (Audio::SoundBuffer* sound : Hymn().sounds) { if (soundEditors[sound].IsVisible()) { soundEditors[sound].Show(); } } ImGui::End(); } bool ResourceList::IsVisible() const { return visible; } void ResourceList::SetVisible(bool visible) { this->visible = visible; } void ResourceList::HideEditors() { for (auto& editor : entityEditors) { editor.second.SetVisible(false); } for (auto& editor : modelEditors) { editor.second.SetVisible(false); } for (auto& editor : textureEditors) { editor.second.SetVisible(false); } for (auto& editor : soundEditors) { editor.second.SetVisible(false); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Thread.h" #if defined( __WINDOWS__ ) #include <Tlhelp32.h> #include <time.h> #include <dbghelp.h> #include <stdio.h> #include <tchar.h> #define DUMP_SIZE_MAX 8000 //max size of our dump #define CALL_TRACE_MAX ( ( DUMP_SIZE_MAX - 2000 ) / ( MAX_PATH + 40 ) ) //max number of traced calls #define NL _T( "\n" ) //new line BOOL WINAPI Get_Module_By_Ret_Addr( PBYTE Ret_Addr, CHAR* Module_Name, PBYTE & Module_Addr ) { __ENTER_FUNCTION MODULEENTRY32 M = { sizeof( M ) }; HANDLE hSnapshot; Module_Name[ 0 ] = 0; hSnapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, 0 ); if ( ( INVALID_HANDLE_VALUE != hSnapshot ) && ::Module32First( hSnapshot, &M ) ) { do { if ( UINT( Ret_Addr - M.modBaseAddr ) < M.modBaseSize ) { lstrcpyn( Module_Name, M.szExePath, MAX_PATH ); Module_Addr = M.modBaseAddr; break; } } while ( ::Module32Next( hSnapshot, &M ) ); } ::CloseHandle( hSnapshot ); return !!Module_Name[0]; __LEAVE_FUNCTION return FALSE ; } VOID CreateExceptionDesc( PEXCEPTION_POINTERS pException, FILE* fp, UINT dwLastError ) { if ( !pException || !fp ) return; EXCEPTION_RECORD & E = *pException->ExceptionRecord; CONTEXT & C = *pException->ContextRecord; //取得异常发生地 TCHAR szModeleInfo[ MAX_PATH ]; TCHAR Module_Name[ MAX_PATH ]; PBYTE Module_Addr; if ( Get_Module_By_Ret_Addr( ( PBYTE )E.ExceptionAddress, Module_Name, Module_Addr ) ) { _sntprintf( szModeleInfo, MAX_PATH, _T( "%s" ), Module_Name ); } else { _sntprintf( szModeleInfo, MAX_PATH, _T( "%08X" ), ( DWORD_PTR )( E.ExceptionAddress ) ); } switch ( E.ExceptionCode ) { //转化后的c++异常 case 0XE000C0DE: { _ftprintf(fp, _T( "C++ Exception\n" ) _T( "\n" ) _T( "Expr: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n"), E.ExceptionInformation[0], E.ExceptionInformation[1], E.ExceptionInformation[2], E.ExceptionInformation[3], E.ExceptionInformation[4], E.ExceptionInformation[5], E.ExceptionInformation[6], E.ExceptionInformation[7], E.ExceptionInformation[8], E.ExceptionInformation[9], E.ExceptionInformation[10], E.ExceptionInformation[11], E.ExceptionInformation[12], E.ExceptionInformation[13], E.ExceptionInformation[14]); } break ; //试图对一个虚地址进行读写 case EXCEPTION_ACCESS_VIOLATION: { // Access violation type - Write/Read. _ftprintf( fp, _T( "\t\tAccess violation\n" ) _T( "\n" ) _T( "@: %s\n" ) _T( "Operate: %s\n" ) _T( "Address: 0x%08X\n" ) _T( "LastError: 0x%08X\n" ), szModeleInfo, ( E.ExceptionInformation[0] ) ? _T( "Write" ) : _T( "Read" ), E.ExceptionInformation[1], dwLastError ); } break; default: { _ftprintf( fp, _T( "\t\tOTHER\n" ) _T( "\n" ) _T( "@: %s\n" ) _T( "Code: 0x%08X\n" ) _T( "LastError: 0x%08X\n" ), szModeleInfo, E.ExceptionCode, dwLastError ); } break ; } } VOID WINAPI Get_Version_Str( FILE* fp ) { OSVERSIONINFOEX V = { sizeof( OSVERSIONINFOEX ) }; //EX for NT 5.0 and later if ( !GetVersionEx( ( POSVERSIONINFO )&V ) ) { ZeroMemory( &V, sizeof( V ) ); V.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ); GetVersionEx( ( POSVERSIONINFO )&V ); } if ( V.dwPlatformId != VER_PLATFORM_WIN32_NT ) V.dwBuildNumber = LOWORD(V.dwBuildNumber ); //for 9x HIWORD(dwBuildNumber) = 0x04xx TCHAR dateBuf[32]; _tstrdate( dateBuf ); TCHAR timeBuf[32]; _tstrtime( timeBuf ); _ftprintf(fp, _T( "==============================================================================\n" ) _T( "Windows: %d.%d.%d, SP %d.%d, Product Type %d\n" ) //SP - service pack, Product Type - VER_NT_WORKSTATION,... _T( "\n") _T( "Time: %s %s\n" ), V.dwMajorVersion, V.dwMinorVersion, V.dwBuildNumber, V.wServicePackMajor, V.wServicePackMinor, V.wProductType, dateBuf, timeBuf ); } VOID Get_Call_Stack( PEXCEPTION_POINTERS pException, FILE* fp ) { TCHAR Module_Name[ MAX_PATH ]; PBYTE Module_Addr = 0; PBYTE Module_Addr_1; #pragma warning(disable: 4200) //nonstandard extension used : zero-sized array in struct/union typedef struct STACK { STACK* Ebp; PBYTE Ret_Addr; UINT Param[0]; } STACK, *PSTACK; #pragma warning(default: 4200) STACK Stack = {0, 0}; PSTACK Ebp; if ( pException ) //fake frame for exception address { Stack.Ebp = ( PSTACK )( DWORD_PTR )pException->ContextRecord->Ebp; Stack.Ret_Addr = ( PBYTE )pException->ExceptionRecord->ExceptionAddress; Ebp = &Stack; } else { Ebp = ( PSTACK )&pException - 1; //frame addr of Get_Call_Stack() // Skip frame of Get_Call_Stack(). if ( !IsBadReadPtr( Ebp, sizeof( PSTACK ) ) ) Ebp = Ebp->Ebp; //caller ebp } // Trace CALL_TRACE_MAX calls maximum - not to exceed DUMP_SIZE_MAX. // Break trace on wrong stack frame. for ( INT Ret_Addr_I = 0; ( Ret_Addr_I < CALL_TRACE_MAX ) && !IsBadReadPtr( Ebp, sizeof( PSTACK ) ) && !IsBadCodePtr( FARPROC( Ebp->Ret_Addr ) ); Ret_Addr_I++, Ebp = Ebp->Ebp ) { // If module with Ebp->Ret_Addr found. if ( Get_Module_By_Ret_Addr( Ebp->Ret_Addr, Module_Name, Module_Addr_1 ) ) { if ( Module_Addr_1 != Module_Addr ) //new module { // Save module's address and full path. Module_Addr = Module_Addr_1; _ftprintf( fp, _T( "%08X %s" )NL, ( LONG_PTR )Module_Addr, Module_Name ); } // Save call offset. _ftprintf( fp, _T( " +%08X" ), Ebp->Ret_Addr - Module_Addr ); // Save 5 params of the call. We don't know the real number of params. if ( pException && !Ret_Addr_I ) //fake frame for exception address _ftprintf( fp, _T( " Exception Offset" )NL ); else if ( !IsBadReadPtr( Ebp, sizeof( PSTACK ) + 5 * sizeof( UINT ) ) ) { _ftprintf( fp, _T( " (%X, %X, %X, %X, %X)" )NL, Ebp->Param[0], Ebp->Param[1], Ebp->Param[2], Ebp->Param[3], Ebp->Param[4] ); } } else _ftprintf( fp, _T( "%08X" )NL, ( LONG_PTR )( Ebp->Ret_Addr ) ); } } VOID Get_Exception_Info( PEXCEPTION_POINTERS pException, FILE* fp, UINT dwLastError ) { CHAR Module_Name[MAX_PATH]; PBYTE Module_Addr; HANDLE hFile; FILETIME Last_Write_Time; FILETIME Local_File_Time; SYSTEMTIME T; Get_Version_Str( fp ); _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ); _ftprintf( fp, _T( "Process: " ) ); GetModuleFileName( NULL, Module_Name, MAX_PATH ); _ftprintf( fp, _T( "%s\n" ) , Module_Name ); // If exception occurred. if ( pException ) { EXCEPTION_RECORD& E = *pException->ExceptionRecord; CONTEXT& C = *pException->ContextRecord; // If module with E.ExceptionAddress found - save its path and date. if ( Get_Module_By_Ret_Addr( ( PBYTE )E.ExceptionAddress, Module_Name, Module_Addr ) ) { _ftprintf( fp, _T( "Module: %s\n" ) , Module_Name ); if ( ( hFile = CreateFile( Module_Name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) ) != INVALID_HANDLE_VALUE ) { if ( GetFileTime( hFile, NULL, NULL, &Last_Write_Time ) ) { FileTimeToLocalFileTime( &Last_Write_Time, &Local_File_Time ); FileTimeToSystemTime( &Local_File_Time, &T ); _ftprintf( fp, _T( "Date Modified: %02d/%02d/%d\n" ) , T.wMonth, T.wDay, T.wYear ); } CloseHandle( hFile ); } } else { _ftprintf( fp, _T( "Exception Addr: %08X\n" ), ( LONG_PTR )( E.ExceptionAddress ) ); } _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ); //加入具体异常解释信息 CreateExceptionDesc( pException, fp, dwLastError ); } _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ); // Save call stack info. _ftprintf( fp, _T( "Call Stack:\n" ) ); Get_Call_Stack( pException, fp ); } BOOL CreateBigInfoFile( PEXCEPTION_POINTERS pException, CHAR* szBigFile, UINT dwLastError ) { __ENTER_FUNCTION if ( !pException ) return FALSE; TCHAR szTempFile[ MAX_PATH ] = {0}; strcpy( szTempFile, "./Server_Dump.txt" ); FILE* fp = _tfopen( szTempFile, _T( "w" ) ); if ( !fp ) return FALSE; Get_Exception_Info( pException, fp, dwLastError ); fclose( fp ); fp = NULL; ::GetShortPathName( szTempFile, szBigFile, MAX_PATH ); if ( 0 == szBigFile[0] ) return FALSE; return TRUE; __LEAVE_FUNCTION return FALSE ; } VOID tProcessException( PEXCEPTION_POINTERS pException ) throw() { //保存最后的错误代码 UINT dwLastError = ::GetLastError(); if ( !pException ) return; //生成完整表述文件 CHAR szBigInfoFile[ MAX_PATH ] = {0}; if ( !CreateBigInfoFile( pException, szBigInfoFile, dwLastError ) ) { return; } //生成dump报告 CHAR szDumpFile[ MAX_PATH ] = {0}; //CreateDumpHelpFile(pException, szDumpFile); } #endif UINT g_QuitThreadCount = 0 ; MyLock g_thread_lock ; Thread::Thread ( ) { __ENTER_FUNCTION m_TID = 0 ; m_Status = Thread::READY ; #if defined( __WINDOWS__ ) m_hThread = NULL ; #endif __LEAVE_FUNCTION } Thread::~Thread () { __ENTER_FUNCTION __LEAVE_FUNCTION } VOID Thread::start () { __ENTER_FUNCTION if ( Thread::READY != m_Status ) return ; #if defined( __LINUX__ ) pthread_create( &m_TID, NULL, MyThreadProcess, this ); #elif defined( __WINDOWS__ ) m_hThread = ::CreateThread( NULL, 0, MyThreadProcess , this, 0, &m_TID ) ; #endif __LEAVE_FUNCTION } VOID Thread::stop () { __ENTER_FUNCTION __LEAVE_FUNCTION } VOID Thread::exit( VOID * retval ) { _MY_TRY { #if defined( __LINUX__ ) pthread_exit( retval ); #elif defined( __WINDOWS__ ) ::CloseHandle( m_hThread ) ; #endif } _MY_CATCH { } } #if defined( __LINUX__ ) VOID * MyThreadProcess ( VOID * derivedThread ) { __ENTER_FUNCTION Thread * thread = (Thread *)derivedThread; if( thread==NULL ) return NULL; // set thread's status to "RUNNING" thread->setStatus(Thread::RUNNING); // here - polymorphism used. (derived::run() called.) thread->run(); // set thread's status to "EXIT" thread->setStatus(Thread::EXIT); //INT ret = 0; //thread->exit(&ret); g_thread_lock.Lock() ; g_QuitThreadCount++ ; g_thread_lock.Unlock() ; __LEAVE_FUNCTION return NULL; // avoid compiler's warning } #elif defined ( __WINDOWS__ ) DWORD WINAPI MyThreadProcess( VOID* derivedThread ) { //__ENTER_FUNCTION __try { Thread * thread = ( Thread * )derivedThread; if ( NULL == thread ) return 0; // set thread's status to "RUNNING" thread->setStatus( Thread::RUNNING ); // here - polymorphism used. (derived::run() called.) thread->run(); // set thread's status to "EXIT" thread->setStatus( Thread::EXIT ); thread->exit( NULL ); g_thread_lock.Lock() ; g_QuitThreadCount++ ; g_thread_lock.Unlock() ; } __except ( tProcessException( GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER ){} //__LEAVE_FUNCTION return 0; // avoid compiler's warning } #endif VOID Thread::run( ) { __ENTER_FUNCTION __LEAVE_FUNCTION } <commit_msg>change the code style for mine<commit_after>#include "stdafx.h" #include "Thread.h" #if defined( __WINDOWS__ ) #include <Tlhelp32.h> #include <time.h> #include <dbghelp.h> #include <stdio.h> #include <tchar.h> #define DUMP_SIZE_MAX 8000 //max size of our dump #define CALL_TRACE_MAX ( ( DUMP_SIZE_MAX - 2000 ) / ( MAX_PATH + 40 ) ) //max number of traced calls #define NL _T( "\n" ) //new line BOOL WINAPI Get_Module_By_Ret_Addr( PBYTE Ret_Addr, CHAR* Module_Name, PBYTE & Module_Addr ) { __ENTER_FUNCTION MODULEENTRY32 M = { sizeof( M ) } ; HANDLE hSnapshot ; Module_Name[ 0 ] = 0 ; hSnapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, 0 ) ; if ( ( INVALID_HANDLE_VALUE != hSnapshot ) && ::Module32First( hSnapshot, &M ) ) { do { if ( UINT( Ret_Addr - M.modBaseAddr ) < M.modBaseSize ) { lstrcpyn( Module_Name, M.szExePath, MAX_PATH ) ; Module_Addr = M.modBaseAddr ; break ; } } while ( ::Module32Next( hSnapshot, &M ) ) ; } ::CloseHandle( hSnapshot ) ; return !!Module_Name[0] ; __LEAVE_FUNCTION return FALSE ; } VOID CreateExceptionDesc( PEXCEPTION_POINTERS pException, FILE* fp, UINT dwLastError ) { if ( !pException || !fp ) return ; EXCEPTION_RECORD & E = *pException->ExceptionRecord ; CONTEXT & C = *pException->ContextRecord ; //取得异常发生地 TCHAR szModeleInfo[ MAX_PATH ] ; TCHAR Module_Name[ MAX_PATH ] ; PBYTE Module_Addr ; if ( Get_Module_By_Ret_Addr( ( PBYTE )E.ExceptionAddress, Module_Name, Module_Addr ) ) { _sntprintf( szModeleInfo, MAX_PATH, _T( "%s" ), Module_Name ) ; } else { _sntprintf( szModeleInfo, MAX_PATH, _T( "%08X" ), ( DWORD_PTR )( E.ExceptionAddress ) ) ; } switch ( E.ExceptionCode ) { //转化后的c++异常 case 0XE000C0DE: { _ftprintf(fp, _T( "C++ Exception\n" ) _T( "\n" ) _T( "Expr: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n"), E.ExceptionInformation[0], E.ExceptionInformation[1], E.ExceptionInformation[2], E.ExceptionInformation[3], E.ExceptionInformation[4], E.ExceptionInformation[5], E.ExceptionInformation[6], E.ExceptionInformation[7], E.ExceptionInformation[8], E.ExceptionInformation[9], E.ExceptionInformation[10], E.ExceptionInformation[11], E.ExceptionInformation[12], E.ExceptionInformation[13], E.ExceptionInformation[14]) ; } break ; //试图对一个虚地址进行读写 case EXCEPTION_ACCESS_VIOLATION: { // Access violation type - Write/Read. _ftprintf( fp, _T( "\t\tAccess violation\n" ) _T( "\n" ) _T( "@: %s\n" ) _T( "Operate: %s\n" ) _T( "Address: 0x%08X\n" ) _T( "LastError: 0x%08X\n" ), szModeleInfo, ( E.ExceptionInformation[0] ) ? _T( "Write" ) : _T( "Read" ), E.ExceptionInformation[1], dwLastError ) ; } break ; default: { _ftprintf( fp, _T( "\t\tOTHER\n" ) _T( "\n" ) _T( "@: %s\n" ) _T( "Code: 0x%08X\n" ) _T( "LastError: 0x%08X\n" ), szModeleInfo, E.ExceptionCode, dwLastError ) ; } break ; } } VOID WINAPI Get_Version_Str( FILE* fp ) { OSVERSIONINFOEX V = { sizeof( OSVERSIONINFOEX ) } ; //EX for NT 5.0 and later if ( !GetVersionEx( ( POSVERSIONINFO )&V ) ) { ZeroMemory( &V, sizeof( V ) ) ; V.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ) ; GetVersionEx( ( POSVERSIONINFO )&V ) ; } if ( V.dwPlatformId != VER_PLATFORM_WIN32_NT ) V.dwBuildNumber = LOWORD(V.dwBuildNumber ) ; //for 9x HIWORD(dwBuildNumber) = 0x04xx TCHAR dateBuf[32] ; _tstrdate( dateBuf ) ; TCHAR timeBuf[32] ; _tstrtime( timeBuf ) ; _ftprintf(fp, _T( "==============================================================================\n" ) _T( "Windows: %d.%d.%d, SP %d.%d, Product Type %d\n" ) //SP - service pack, Product Type - VER_NT_WORKSTATION,... _T( "\n") _T( "Time: %s %s\n" ), V.dwMajorVersion, V.dwMinorVersion, V.dwBuildNumber, V.wServicePackMajor, V.wServicePackMinor, V.wProductType, dateBuf, timeBuf ) ; } VOID Get_Call_Stack( PEXCEPTION_POINTERS pException, FILE* fp ) { TCHAR Module_Name[ MAX_PATH ] ; PBYTE Module_Addr = 0 ; PBYTE Module_Addr_1 ; #pragma warning(disable: 4200) //nonstandard extension used : zero-sized array in struct/union typedef struct STACK { STACK* Ebp ; PBYTE Ret_Addr ; UINT Param[0] ; } STACK, *PSTACK ; #pragma warning(default: 4200) STACK Stack = {0, 0} ; PSTACK Ebp ; if ( pException ) //fake frame for exception address { Stack.Ebp = ( PSTACK )( DWORD_PTR )pException->ContextRecord->Ebp ; Stack.Ret_Addr = ( PBYTE )pException->ExceptionRecord->ExceptionAddress ; Ebp = &Stack ; } else { Ebp = ( PSTACK )&pException - 1 ; //frame addr of Get_Call_Stack() // Skip frame of Get_Call_Stack(). if ( !IsBadReadPtr( Ebp, sizeof( PSTACK ) ) ) Ebp = Ebp->Ebp ; //caller ebp } // Trace CALL_TRACE_MAX calls maximum - not to exceed DUMP_SIZE_MAX. // Break trace on wrong stack frame. for ( INT Ret_Addr_I = 0 ; ( Ret_Addr_I < CALL_TRACE_MAX ) && !IsBadReadPtr( Ebp, sizeof( PSTACK ) ) && !IsBadCodePtr( FARPROC( Ebp->Ret_Addr ) ) ; Ret_Addr_I++, Ebp = Ebp->Ebp ) { // If module with Ebp->Ret_Addr found. if ( Get_Module_By_Ret_Addr( Ebp->Ret_Addr, Module_Name, Module_Addr_1 ) ) { if ( Module_Addr_1 != Module_Addr ) //new module { // Save module's address and full path. Module_Addr = Module_Addr_1 ; _ftprintf( fp, _T( "%08X %s" )NL, ( LONG_PTR )Module_Addr, Module_Name ) ; } // Save call offset. _ftprintf( fp, _T( " +%08X" ), Ebp->Ret_Addr - Module_Addr ) ; // Save 5 params of the call. We don't know the real number of params. if ( pException && !Ret_Addr_I ) //fake frame for exception address _ftprintf( fp, _T( " Exception Offset" )NL ) ; else if ( !IsBadReadPtr( Ebp, sizeof( PSTACK ) + 5 * sizeof( UINT ) ) ) { _ftprintf( fp, _T( " (%X, %X, %X, %X, %X)" )NL, Ebp->Param[0], Ebp->Param[1], Ebp->Param[2], Ebp->Param[3], Ebp->Param[4] ) ; } } else _ftprintf( fp, _T( "%08X" )NL, ( LONG_PTR )( Ebp->Ret_Addr ) ) ; } } VOID Get_Exception_Info( PEXCEPTION_POINTERS pException, FILE* fp, UINT dwLastError ) { CHAR Module_Name[MAX_PATH] ; PBYTE Module_Addr ; HANDLE hFile ; FILETIME Last_Write_Time ; FILETIME Local_File_Time ; SYSTEMTIME T ; Get_Version_Str( fp ) ; _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ) ; _ftprintf( fp, _T( "Process: " ) ) ; GetModuleFileName( NULL, Module_Name, MAX_PATH ) ; _ftprintf( fp, _T( "%s\n" ) , Module_Name ) ; // If exception occurred. if ( pException ) { EXCEPTION_RECORD& E = *pException->ExceptionRecord ; CONTEXT& C = *pException->ContextRecord ; // If module with E.ExceptionAddress found - save its path and date. if ( Get_Module_By_Ret_Addr( ( PBYTE )E.ExceptionAddress, Module_Name, Module_Addr ) ) { _ftprintf( fp, _T( "Module: %s\n" ) , Module_Name ) ; if ( ( hFile = CreateFile( Module_Name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ) ) != INVALID_HANDLE_VALUE ) { if ( GetFileTime( hFile, NULL, NULL, &Last_Write_Time ) ) { FileTimeToLocalFileTime( &Last_Write_Time, &Local_File_Time ) ; FileTimeToSystemTime( &Local_File_Time, &T ) ; _ftprintf( fp, _T( "Date Modified: %02d/%02d/%d\n" ) , T.wMonth, T.wDay, T.wYear ) ; } CloseHandle( hFile ) ; } } else { _ftprintf( fp, _T( "Exception Addr: %08X\n" ), ( LONG_PTR )( E.ExceptionAddress ) ) ; } _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ) ; //加入具体异常解释信息 CreateExceptionDesc( pException, fp, dwLastError ) ; } _ftprintf( fp, _T( "------------------------------------------------------------------------------\n" ) ) ; // Save call stack info. _ftprintf( fp, _T( "Call Stack:\n" ) ) ; Get_Call_Stack( pException, fp ) ; } BOOL CreateBigInfoFile( PEXCEPTION_POINTERS pException, CHAR* szBigFile, UINT dwLastError ) { __ENTER_FUNCTION if ( !pException ) return FALSE ; TCHAR szTempFile[ MAX_PATH ] = {0} ; strcpy( szTempFile, "./Server_Dump.txt" ) ; FILE* fp = _tfopen( szTempFile, _T( "w" ) ) ; if ( !fp ) return FALSE ; Get_Exception_Info( pException, fp, dwLastError ) ; fclose( fp ) ; fp = NULL ; ::GetShortPathName( szTempFile, szBigFile, MAX_PATH ) ; if ( 0 == szBigFile[0] ) return FALSE ; return TRUE ; __LEAVE_FUNCTION return FALSE ; } VOID tProcessException( PEXCEPTION_POINTERS pException ) throw() { //保存最后的错误代码 UINT dwLastError = ::GetLastError() ; if ( !pException ) return ; //生成完整表述文件 CHAR szBigInfoFile[ MAX_PATH ] = {0} ; if ( !CreateBigInfoFile( pException, szBigInfoFile, dwLastError ) ) { return ; } //生成dump报告 CHAR szDumpFile[ MAX_PATH ] = {0} ; //CreateDumpHelpFile(pException, szDumpFile) ; } #endif UINT g_QuitThreadCount = 0 ; MyLock g_thread_lock ; Thread::Thread ( ) { __ENTER_FUNCTION m_TID = 0 ; m_Status = Thread::READY ; #if defined( __WINDOWS__ ) m_hThread = NULL ; #endif __LEAVE_FUNCTION } Thread::~Thread () { __ENTER_FUNCTION __LEAVE_FUNCTION } VOID Thread::start () { __ENTER_FUNCTION if ( Thread::READY != m_Status ) return ; #if defined( __LINUX__ ) pthread_create( &m_TID, NULL, MyThreadProcess, this ) ; #elif defined( __WINDOWS__ ) m_hThread = ::CreateThread( NULL, 0, MyThreadProcess , this, 0, &m_TID ) ; #endif __LEAVE_FUNCTION } VOID Thread::stop () { __ENTER_FUNCTION __LEAVE_FUNCTION } VOID Thread::exit( VOID * retval ) { _MY_TRY { #if defined( __LINUX__ ) pthread_exit( retval ) ; #elif defined( __WINDOWS__ ) ::CloseHandle( m_hThread ) ; #endif } _MY_CATCH { } } #if defined( __LINUX__ ) VOID * MyThreadProcess ( VOID * derivedThread ) { __ENTER_FUNCTION Thread* thread = ( Thread* )derivedThread ; if ( NULL == thread ) return NULL ; // set thread's status to "RUNNING" thread->setStatus( Thread::RUNNING ) ; // here - polymorphism used. (derived::run() called.) thread->run() ; // set thread's status to "EXIT" thread->setStatus( Thread::EXIT ) ; //INT ret = 0 ; //thread->exit(&ret) ; g_thread_lock.Lock() ; g_QuitThreadCount++ ; g_thread_lock.Unlock() ; __LEAVE_FUNCTION return NULL ; // avoid compiler's warning } #elif defined ( __WINDOWS__ ) DWORD WINAPI MyThreadProcess( VOID* derivedThread ) { //__ENTER_FUNCTION __try { Thread * thread = ( Thread * )derivedThread ; if ( NULL == thread ) return 0 ; // set thread's status to "RUNNING" thread->setStatus( Thread::RUNNING ) ; // here - polymorphism used. (derived::run() called.) thread->run() ; // set thread's status to "EXIT" thread->setStatus( Thread::EXIT ) ; thread->exit( NULL ) ; g_thread_lock.Lock() ; g_QuitThreadCount++ ; g_thread_lock.Unlock() ; } __except ( tProcessException( GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER ){} //__LEAVE_FUNCTION return 0 ; // avoid compiler's warning } #endif VOID Thread::run() { __ENTER_FUNCTION __LEAVE_FUNCTION } <|endoftext|>
<commit_before>#include "Managers.hpp" #include "ResourceManager.hpp" #include "RenderManager.hpp" #include "ParticleManager.hpp" #include "PhysicsManager.hpp" #include "SoundManager.hpp" #include "ScriptManager.hpp" #include "DebugDrawingManager.hpp" #include "ProfilingManager.hpp" #include "../Component/SuperComponent.hpp" Hub::Hub() { } Hub& Managers() { static Hub instance; return instance; } void Hub::StartUp() { resourceManager = new ResourceManager(); renderManager = new RenderManager(); particleManager = new ParticleManager(); physicsManager = new PhysicsManager(); soundManager = new SoundManager(); scriptManager = new ScriptManager(); debugDrawingManager = new DebugDrawingManager(); profilingManager = new ProfilingManager(); } void Hub::ShutDown() { delete profilingManager; delete debugDrawingManager; delete scriptManager; delete soundManager; delete renderManager; delete particleManager; delete physicsManager; delete resourceManager; } void Hub::AddComponent(Component::SuperComponent* component, const std::type_info* componentType) { switch (component->GetManager()) { case Component::SuperComponent::MANAGER::Profiling: profilingManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::DebugDrawing: debugDrawingManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Script: scriptManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Sound: soundManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Render: renderManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Particle: particleManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Physics: physicsManager->AddComponent(component, componentType); break; case Component::SuperComponent::MANAGER::Resource: resourceManager->AddComponent(component, componentType); break; default: break; } } void Hub::ClearComponents() { resourceManager->ClearComponents(); renderManager->ClearComponents(); particleManager->ClearComponents(); physicsManager->ClearComponents(); soundManager->ClearComponents(); scriptManager->ClearComponents(); debugDrawingManager->ClearComponents(); profilingManager->ClearComponents(); } void Hub::ClearKilledComponents() { resourceManager->ClearKilledComponents(); renderManager->ClearKilledComponents(); particleManager->ClearKilledComponents(); physicsManager->ClearKilledComponents(); soundManager->ClearKilledComponents(); scriptManager->ClearKilledComponents(); debugDrawingManager->ClearKilledComponents(); profilingManager->ClearKilledComponents(); } <commit_msg>Temporary solution for putting the components in the right place<commit_after>#include "Managers.hpp" #include "ResourceManager.hpp" #include "RenderManager.hpp" #include "ParticleManager.hpp" #include "PhysicsManager.hpp" #include "SoundManager.hpp" #include "ScriptManager.hpp" #include "DebugDrawingManager.hpp" #include "ProfilingManager.hpp" #include "../Component/SuperComponent.hpp" #include "Utility/Log.hpp" Hub::Hub() { } Hub& Managers() { static Hub instance; return instance; } void Hub::StartUp() { resourceManager = new ResourceManager(); renderManager = new RenderManager(); particleManager = new ParticleManager(); physicsManager = new PhysicsManager(); soundManager = new SoundManager(); scriptManager = new ScriptManager(); debugDrawingManager = new DebugDrawingManager(); profilingManager = new ProfilingManager(); } void Hub::ShutDown() { delete profilingManager; delete debugDrawingManager; delete scriptManager; delete soundManager; delete renderManager; delete particleManager; delete physicsManager; delete resourceManager; } void Hub::AddComponent(Component::SuperComponent* component, const std::type_info* componentType) { std::string name = componentType->name(); if (name == "class Component::Animation *") renderManager->AddComponent(component, componentType); else if (name == "class Component::DirectionalLight *") renderManager->AddComponent(component, componentType); else if (name == "class Component::Lens *") renderManager->AddComponent(component, componentType); else if (name == "class Component::Listener *") soundManager->AddComponent(component, componentType); else if (name == "class Component::Material *") renderManager->AddComponent(component, componentType); else if (name == "class Component::Mesh *") renderManager->AddComponent(component, componentType); else if (name == "class Component::ParticleEmitter *") particleManager->AddComponent(component, componentType); else if (name == "class Component::Physics *") physicsManager->AddComponent(component, componentType); else if (name == "class Component::PointLight *") renderManager->AddComponent(component, componentType); else if (name == "class Component::Script *") scriptManager->AddComponent(component, componentType); else if (name == "class Component::SoundSource *") soundManager->AddComponent(component, componentType); else if (name == "class Component::SpotLight *") renderManager->AddComponent(component, componentType); else Log() << name << " not assigned to a manager!" << "\n"; } void Hub::ClearComponents() { resourceManager->ClearComponents(); renderManager->ClearComponents(); particleManager->ClearComponents(); physicsManager->ClearComponents(); soundManager->ClearComponents(); scriptManager->ClearComponents(); debugDrawingManager->ClearComponents(); profilingManager->ClearComponents(); } void Hub::ClearKilledComponents() { resourceManager->ClearKilledComponents(); renderManager->ClearKilledComponents(); particleManager->ClearKilledComponents(); physicsManager->ClearKilledComponents(); soundManager->ClearKilledComponents(); scriptManager->ClearKilledComponents(); debugDrawingManager->ClearKilledComponents(); profilingManager->ClearKilledComponents(); } <|endoftext|>
<commit_before>/** KDE Certificate Manager by Kalle Dalheimer <[email protected]>, Jesper K. Pedersen <[email protected]> and Steffen Hansen <[email protected]> Copyright (C) 2002 by Klarlvdalens Datakonsult AB This software is licensed under the GPL. */ #include <kapplication.h> #include "certmanager.h" #include <kcmdlineargs.h> #include <kmessagebox.h> #include <klocale.h> #include <kaboutdata.h> #include <cryptplugwrapper.h> CryptPlugWrapper* pWrapper; static const char* KGPGCERTMANAGER_VERSION = I18N_NOOP("0.9"); static const char* DESCRIPTION = I18N_NOOP("Certificate Manager"); int main( int argc, char** argv ) { KAboutData aboutData( "kgpgcertmanager", I18N_NOOP("KGpgCertManager"), KGPGCERTMANAGER_VERSION, DESCRIPTION, KAboutData::License_GPL, "(c) 2002, Steffen Hansen, Jesper Pedersen,\nKalle Dalheimer, Klarlvdalens Datakonsult AB"); aboutData.addAuthor( "Steffen Hansen", I18N_NOOP("Current Maintainer"), "[email protected]" ); aboutData.addAuthor( "Kalle Dalheimer", 0, "[email protected]" ); aboutData.addAuthor( "Jesper Pedersen", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &aboutData); static KCmdLineOptions options[] = { { "+name", I18N_NOOP("The name of the plugin"), 0 }, { "+lib" , I18N_NOOP("The library of the plugin"), 0 }, { "external" , I18N_NOOP("Search for external certificates initially"), 0 }, { "query " , I18N_NOOP("Initial query string"), 0 }, { 0, 0, 0 } // End of options. }; KCmdLineArgs::addCmdLineOptions( options ); KApplication app; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if( args->count() < 2 ) { KMessageBox::error( 0, i18n( "<qt>Certificate Manager called incorrectly.<br>Usage: certmanager <em>plugin-name</em> <em>plugin-lib</em><br>Certificate Manager will terminate now.</qt>" ), i18n( "Certificate Manager Error" ) ); return -1; } QString pluginName = QString::fromLocal8Bit( args->arg( 0 ) ); QString pluginLib = QString::fromLocal8Bit( args->arg( 1 ) ); pWrapper = new CryptPlugWrapper( 0, pluginName, pluginLib, QString::null, true ); CryptPlugWrapper::InitStatus initStatus; QString errorText; if( !pWrapper->initialize( &initStatus, &errorText ) ) { KMessageBox::error( 0, i18n( "<qt>The crypto plugin could not be initialized; the error message was %1.<br>Certificate Manager will terminate now.</qt>" ).arg( errorText ), i18n( "Certificate Manager Error" ) ); return -2; } CertManager* manager = new CertManager( args->isSet("external"), QString::fromLocal8Bit(args->getOption("query")) ); args->clear(); manager->show(); QObject::connect( qApp, SIGNAL( lastWindowClosed() ), qApp, SLOT( quit() ) ); int ret = app.exec(); delete pWrapper; return ret; } <commit_msg>add a const and give KDAB it's a-umlaut (strings are in UTF-8)<commit_after>/** KDE Certificate Manager by Kalle Dalheimer <[email protected]>, Jesper K. Pedersen <[email protected]> and Steffen Hansen <[email protected]> Copyright (C) 2002 by Klarlvdalens Datakonsult AB This software is licensed under the GPL. */ #include <kapplication.h> #include "certmanager.h" #include <kcmdlineargs.h> #include <kmessagebox.h> #include <klocale.h> #include <kaboutdata.h> #include <cryptplugwrapper.h> CryptPlugWrapper* pWrapper; static const char* KGPGCERTMANAGER_VERSION = I18N_NOOP("0.9"); static const char* DESCRIPTION = I18N_NOOP("Certificate Manager"); int main( int argc, char** argv ) { KAboutData aboutData( "kgpgcertmanager", I18N_NOOP("KGpgCertManager"), KGPGCERTMANAGER_VERSION, DESCRIPTION, KAboutData::License_GPL, "(c) 2002, Steffen Hansen, Jesper Pedersen,\n" "Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB"); aboutData.addAuthor( "Steffen Hansen", I18N_NOOP("Current Maintainer"), "[email protected]" ); aboutData.addAuthor( "Kalle Dalheimer", 0, "[email protected]" ); aboutData.addAuthor( "Jesper Pedersen", 0, "[email protected]" ); KCmdLineArgs::init(argc, argv, &aboutData); static const KCmdLineOptions options[] = { { "+name", I18N_NOOP("The name of the plugin"), 0 }, { "+lib" , I18N_NOOP("The library of the plugin"), 0 }, { "external" , I18N_NOOP("Search for external certificates initially"), 0 }, { "query " , I18N_NOOP("Initial query string"), 0 }, { 0, 0, 0 } // End of options. }; KCmdLineArgs::addCmdLineOptions( options ); KApplication app; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if( args->count() < 2 ) { KMessageBox::error( 0, i18n( "<qt>Certificate Manager called incorrectly.<br>Usage: certmanager <em>plugin-name</em> <em>plugin-lib</em><br>Certificate Manager will terminate now.</qt>" ), i18n( "Certificate Manager Error" ) ); return -1; } QString pluginName = QString::fromLocal8Bit( args->arg( 0 ) ); QString pluginLib = QString::fromLocal8Bit( args->arg( 1 ) ); pWrapper = new CryptPlugWrapper( 0, pluginName, pluginLib, QString::null, true ); CryptPlugWrapper::InitStatus initStatus; QString errorText; if( !pWrapper->initialize( &initStatus, &errorText ) ) { KMessageBox::error( 0, i18n( "<qt>The crypto plugin could not be initialized; the error message was %1.<br>Certificate Manager will terminate now.</qt>" ).arg( errorText ), i18n( "Certificate Manager Error" ) ); return -2; } CertManager* manager = new CertManager( args->isSet("external"), QString::fromLocal8Bit(args->getOption("query")) ); args->clear(); manager->show(); QObject::connect( qApp, SIGNAL( lastWindowClosed() ), qApp, SLOT( quit() ) ); int ret = app.exec(); delete pWrapper; return ret; } <|endoftext|>
<commit_before> /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /****************** <SNX heading BEGIN do not edit this line> ***************** * * Juggler Juggler * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <SNX heading END do not edit this line> ******************/ #include <iostream> #include <unistd.h> #include "snx/sonix.h" // interface #include "snx/FileIO.h" void usage( int argc, char* argv[] ) { std::cout<<"Usage: "<<argv[0]<<" apiname filename\n"<<std::flush; std::cout<<" "<<argv[0]<<" OpenAL sample.wav\n"<<std::flush; std::cout<<" "<<argv[0]<<" JugglerWorks sample.aifc\n"<<std::flush; } int main( int argc, char* argv[] ) { char bok[] = "../../data/sample.wav"; std::string filename, api; if (argc == 1 || argc == 2) { api = "OpenAL"; filename = bok; usage( argc, argv ); } if (argc == 2 || argc == 3) { api = argv[1]; } if (argc == 3) { filename = argv[2]; } if (argc > 3) { usage( argc, argv ); return 0; } if (!snxFileIO::fileExists( filename.c_str() )) { std::cout << "File not found: " << filename << "\n" << std::flush; return 0; } snx::SoundInfo si; si.filename = filename; si.datasource = snx::SoundInfo::FILESYSTEM; std::cout<<"sonix: \n" << std::flush; //snx.startAPI(); std::cout<<"associate: \n" << std::flush; sonix::instance()->configure( "kevin", si ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 1 ); sonix::instance()->changeAPI( api ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 3 ); sonix::instance()->changeAPI( "stub" ); sleep( 1 ); sonix::instance()->changeAPI( api ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 3 ); sonix::instance()->changeAPI( "stub" ); return 1; } /* #include "snxSoundFactory.h" #include "snxSoundImplementation.h" #include "snxJugglerWorksSoundImplementation.h" #include "snxSoundInfo.h" #include "snxOpenALSoundImplementation.h" #include "snxStubSoundImplementation.h" */ <commit_msg>fixed some typos from the AJ to SNX name change..<commit_after> /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ /****************** <SNX heading BEGIN do not edit this line> ***************** * * Juggler Juggler * * Original Authors: * Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <SNX heading END do not edit this line> ******************/ #include <iostream> #include <unistd.h> #include "snx/sonix.h" // interface #include "snx/FileIO.h" void usage( int argc, char* argv[] ) { std::cout<<"Usage: "<<argv[0]<<" apiname filename\n"<<std::flush; std::cout<<" "<<argv[0]<<" OpenAL sample.wav\n"<<std::flush; std::cout<<" "<<argv[0]<<" AudioWorks sample.aifc\n"<<std::flush; } int main( int argc, char* argv[] ) { char bok[] = "../../data/sample.wav"; std::string filename, api; if (argc == 1 || argc == 2) { api = "OpenAL"; filename = bok; usage( argc, argv ); } if (argc == 2 || argc == 3) { api = argv[1]; } if (argc == 3) { filename = argv[2]; } if (argc > 3) { usage( argc, argv ); return 0; } if (!snxFileIO::fileExists( filename.c_str() )) { std::cout << "File not found: " << filename << "\n" << std::flush; return 0; } snx::SoundInfo si; si.filename = filename; si.datasource = snx::SoundInfo::FILESYSTEM; std::cout<<"sonix: \n" << std::flush; //snx.startAPI(); std::cout<<"associate: \n" << std::flush; sonix::instance()->configure( "kevin", si ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 1 ); sonix::instance()->changeAPI( api ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 3 ); sonix::instance()->changeAPI( "stub" ); sleep( 1 ); sonix::instance()->changeAPI( api ); std::cout<<"trigger: \n" << std::flush; sonix::instance()->trigger( "kevin" ); std::cout<<"sleep: \n" << std::flush; sleep( 3 ); sonix::instance()->changeAPI( "stub" ); return 1; } /* #include "snxSoundFactory.h" #include "snxSoundImplementation.h" #include "snxAudioWorksSoundImplementation.h" #include "snxSoundInfo.h" #include "snxOpenALSoundImplementation.h" #include "snxStubSoundImplementation.h" */ <|endoftext|>
<commit_before><commit_msg>remove order dependence on simulation_world_service_test<commit_after><|endoftext|>
<commit_before>#ifndef __LARGE_BUF_HPP__ #define __LARGE_BUF_HPP__ #include "buffer_cache/buffer_cache.hpp" #include "config/args.hpp" class large_buf_t; struct large_buf_available_callback_t : public intrusive_list_node_t<large_buf_available_callback_t> { virtual ~large_buf_available_callback_t() {} virtual void on_large_buf_available(large_buf_t *large_buf) = 0; }; struct large_value_completed_callback { virtual void on_large_value_completed(bool success) = 0; virtual ~large_value_completed_callback() {} }; // struct large_buf_ref is defined in buffer_cache/types.hpp. struct large_buf_internal { block_magic_t magic; block_id_t kids[]; static const block_magic_t expected_magic; }; struct large_buf_leaf { block_magic_t magic; byte buf[]; static const block_magic_t expected_magic; }; struct buftree_t { #ifndef NDEBUG int level; // a positive number #endif buf_t *buf; std::vector<buftree_t *> children; }; struct tree_available_callback_t; class large_buf_t { private: large_buf_ref *root_ref; lbref_limit_t root_ref_limit; std::vector<buftree_t *> roots; access_t access; int num_to_acquire; large_buf_available_callback_t *callback; transaction_t *transaction; block_size_t block_size; public: // XXX Should this be private? enum state_t { not_loaded, loading, loaded, deleted, released }; state_t state; #ifndef NDEBUG int64_t num_bufs; #endif // TODO: Take care of private methods and friend classes and all that. public: explicit large_buf_t(transaction_t *txn); ~large_buf_t(); void allocate(int64_t _size, large_buf_ref *refout, lbref_limit_t ref_limit); void acquire(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_rhs(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_lhs(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_for_delete(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, large_buf_available_callback_t *callback_); // refsize_adjustment_out parameter forces callers to recognize // that the size may change, so hopefully they'll update their // btree_value size field appropriately. void append(int64_t extra_size, int *refsize_adjustment_out); void prepend(int64_t extra_size, int *refsize_adjustment_out); void fill_at(int64_t pos, const void *data, int64_t fill_size); void read_at(int64_t pos, void *data_out, int64_t read_size); void unappend(int64_t extra_size, int *refsize_adjustment_out); void unprepend(int64_t extra_size, int *refsize_adjustment_out); int64_t pos_to_ix(int64_t pos); uint16_t pos_to_seg_pos(int64_t pos); void mark_deleted(); void release(); void assert_thread() const { transaction->assert_thread(); } // TODO get rid of this function, why do we need it if the user of // the large buf owns the root ref? const large_buf_ref *get_root_ref() const { rassert(roots[0] == NULL || roots[0]->level == num_sublevels(root_ref->offset + root_ref->size)); return root_ref; } int64_t get_num_segments(); uint16_t segment_size(int64_t ix); const byte *get_segment(int64_t num, uint16_t *seg_size); byte *get_segment_write(int64_t num, uint16_t *seg_size); void on_block_available(buf_t *buf); void index_acquired(buf_t *buf); void segment_acquired(buf_t *buf, uint16_t ix); void buftree_acquired(buftree_t *tr, int index); friend struct acquire_buftree_fsm_t; static int64_t cache_size_to_leaf_bytes(block_size_t block_size); static int64_t cache_size_to_internal_kids(block_size_t block_size); static int64_t compute_max_offset(block_size_t block_size, int levels); static int compute_num_levels(block_size_t block_size, int64_t end_offset); static int compute_num_sublevels(block_size_t block_size, int64_t end_offset, lbref_limit_t ref_limit); static int compute_large_buf_ref_num_inlined(block_size_t block_size, int64_t end_offset, lbref_limit_t ref_limit); private: int64_t num_leaf_bytes() const; int64_t num_internal_kids() const; int64_t max_offset(int levels) const; int num_levels(int64_t end_offset) const; int num_sublevels(int64_t end_offset) const; buftree_t *allocate_buftree(int64_t size, int64_t offset, int levels, block_id_t *block_id); buftree_t *acquire_buftree(block_id_t block_id, int64_t offset, int64_t size, int levels, tree_available_callback_t *cb); void acquire_slice(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, int64_t slice_offset, int64_t slice_size, large_buf_available_callback_t *callback_, bool should_load_leaves_ = true); void read_trees_at(const std::vector<buftree_t *>& trees, int64_t pos, byte *data_out, int64_t read_size, int sublevels); void read_tree_at(buftree_t *tr, int64_t pos, byte *data_out, int64_t read_size, int levels); void fill_trees_at(const std::vector<buftree_t *>& trees, int64_t pos, const byte *data, int64_t fill_size, int sublevels); void fill_tree_at(buftree_t *tr, int64_t pos, const byte *data, int64_t fill_size, int levels); void adds_level(block_id_t *ids #ifndef NDEBUG , int nextlevels #endif ); void allocate_part_of_tree(buftree_t *tr, int64_t offset, int64_t size, int levels); void allocates_part_of_tree(std::vector<buftree_t *> *ptrs, block_id_t *block_ids, int64_t offset, int64_t size, int64_t sublevels); buftree_t *walk_tree_structure(buftree_t *tr, int64_t offset, int64_t size, int levels, void (*bufdoer)(large_buf_t *, buf_t *), buftree_t *(*buftree_cleaner)(buftree_t *)); void walk_tree_structures(std::vector<buftree_t *> *trs, int64_t offset, int64_t size, int sublevels, void (*bufdoer)(large_buf_t *, buf_t *), buftree_t *(*buftree_cleaner)(buftree_t *)); void delete_tree_structures(std::vector<buftree_t *> *trees, int64_t offset, int64_t size, int sublevels); void only_mark_deleted_tree_structures(std::vector<buftree_t *> *trees, int64_t offset, int64_t size, int sublevels); void release_tree_structures(std::vector<buftree_t *> *trs, int64_t offset, int64_t size, int sublevels); buf_t *get_segment_buf(int64_t ix, uint16_t *seg_size, uint16_t *seg_offset); void removes_level(block_id_t *ids, int copyees); int try_shifting(std::vector<buftree_t *> *trs, block_id_t *block_ids, int64_t offset, int64_t size, int64_t stepsize); }; #endif // __LARGE_BUF_HPP__ <commit_msg>Added DISABLE_COPYING to large_buf_t.<commit_after>#ifndef __LARGE_BUF_HPP__ #define __LARGE_BUF_HPP__ #include "buffer_cache/buffer_cache.hpp" #include "config/args.hpp" class large_buf_t; struct large_buf_available_callback_t : public intrusive_list_node_t<large_buf_available_callback_t> { virtual ~large_buf_available_callback_t() {} virtual void on_large_buf_available(large_buf_t *large_buf) = 0; }; struct large_value_completed_callback { virtual void on_large_value_completed(bool success) = 0; virtual ~large_value_completed_callback() {} }; // struct large_buf_ref is defined in buffer_cache/types.hpp. struct large_buf_internal { block_magic_t magic; block_id_t kids[]; static const block_magic_t expected_magic; }; struct large_buf_leaf { block_magic_t magic; byte buf[]; static const block_magic_t expected_magic; }; struct buftree_t { #ifndef NDEBUG int level; // a positive number #endif buf_t *buf; std::vector<buftree_t *> children; }; struct tree_available_callback_t; class large_buf_t { private: large_buf_ref *root_ref; lbref_limit_t root_ref_limit; std::vector<buftree_t *> roots; access_t access; int num_to_acquire; large_buf_available_callback_t *callback; transaction_t *transaction; block_size_t block_size; public: // XXX Should this be private? enum state_t { not_loaded, loading, loaded, deleted, released }; state_t state; #ifndef NDEBUG int64_t num_bufs; #endif // TODO: Take care of private methods and friend classes and all that. public: explicit large_buf_t(transaction_t *txn); ~large_buf_t(); void allocate(int64_t _size, large_buf_ref *refout, lbref_limit_t ref_limit); void acquire(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_rhs(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_lhs(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, large_buf_available_callback_t *callback_); void acquire_for_delete(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, large_buf_available_callback_t *callback_); // refsize_adjustment_out parameter forces callers to recognize // that the size may change, so hopefully they'll update their // btree_value size field appropriately. void append(int64_t extra_size, int *refsize_adjustment_out); void prepend(int64_t extra_size, int *refsize_adjustment_out); void fill_at(int64_t pos, const void *data, int64_t fill_size); void read_at(int64_t pos, void *data_out, int64_t read_size); void unappend(int64_t extra_size, int *refsize_adjustment_out); void unprepend(int64_t extra_size, int *refsize_adjustment_out); int64_t pos_to_ix(int64_t pos); uint16_t pos_to_seg_pos(int64_t pos); void mark_deleted(); void release(); void assert_thread() const { transaction->assert_thread(); } // TODO get rid of this function, why do we need it if the user of // the large buf owns the root ref? const large_buf_ref *get_root_ref() const { rassert(roots[0] == NULL || roots[0]->level == num_sublevels(root_ref->offset + root_ref->size)); return root_ref; } int64_t get_num_segments(); uint16_t segment_size(int64_t ix); const byte *get_segment(int64_t num, uint16_t *seg_size); byte *get_segment_write(int64_t num, uint16_t *seg_size); void on_block_available(buf_t *buf); void index_acquired(buf_t *buf); void segment_acquired(buf_t *buf, uint16_t ix); void buftree_acquired(buftree_t *tr, int index); friend struct acquire_buftree_fsm_t; static int64_t cache_size_to_leaf_bytes(block_size_t block_size); static int64_t cache_size_to_internal_kids(block_size_t block_size); static int64_t compute_max_offset(block_size_t block_size, int levels); static int compute_num_levels(block_size_t block_size, int64_t end_offset); static int compute_num_sublevels(block_size_t block_size, int64_t end_offset, lbref_limit_t ref_limit); static int compute_large_buf_ref_num_inlined(block_size_t block_size, int64_t end_offset, lbref_limit_t ref_limit); private: int64_t num_leaf_bytes() const; int64_t num_internal_kids() const; int64_t max_offset(int levels) const; int num_levels(int64_t end_offset) const; int num_sublevels(int64_t end_offset) const; buftree_t *allocate_buftree(int64_t size, int64_t offset, int levels, block_id_t *block_id); buftree_t *acquire_buftree(block_id_t block_id, int64_t offset, int64_t size, int levels, tree_available_callback_t *cb); void acquire_slice(large_buf_ref *root_ref_, lbref_limit_t ref_limit_, access_t access_, int64_t slice_offset, int64_t slice_size, large_buf_available_callback_t *callback_, bool should_load_leaves_ = true); void read_trees_at(const std::vector<buftree_t *>& trees, int64_t pos, byte *data_out, int64_t read_size, int sublevels); void read_tree_at(buftree_t *tr, int64_t pos, byte *data_out, int64_t read_size, int levels); void fill_trees_at(const std::vector<buftree_t *>& trees, int64_t pos, const byte *data, int64_t fill_size, int sublevels); void fill_tree_at(buftree_t *tr, int64_t pos, const byte *data, int64_t fill_size, int levels); void adds_level(block_id_t *ids #ifndef NDEBUG , int nextlevels #endif ); void allocate_part_of_tree(buftree_t *tr, int64_t offset, int64_t size, int levels); void allocates_part_of_tree(std::vector<buftree_t *> *ptrs, block_id_t *block_ids, int64_t offset, int64_t size, int64_t sublevels); buftree_t *walk_tree_structure(buftree_t *tr, int64_t offset, int64_t size, int levels, void (*bufdoer)(large_buf_t *, buf_t *), buftree_t *(*buftree_cleaner)(buftree_t *)); void walk_tree_structures(std::vector<buftree_t *> *trs, int64_t offset, int64_t size, int sublevels, void (*bufdoer)(large_buf_t *, buf_t *), buftree_t *(*buftree_cleaner)(buftree_t *)); void delete_tree_structures(std::vector<buftree_t *> *trees, int64_t offset, int64_t size, int sublevels); void only_mark_deleted_tree_structures(std::vector<buftree_t *> *trees, int64_t offset, int64_t size, int sublevels); void release_tree_structures(std::vector<buftree_t *> *trs, int64_t offset, int64_t size, int sublevels); buf_t *get_segment_buf(int64_t ix, uint16_t *seg_size, uint16_t *seg_offset); void removes_level(block_id_t *ids, int copyees); int try_shifting(std::vector<buftree_t *> *trs, block_id_t *block_ids, int64_t offset, int64_t size, int64_t stepsize); DISABLE_COPYING(large_buf_t); }; #endif // __LARGE_BUF_HPP__ <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface headers #include "HUDuiServerInfo.h" #include "playing.h" #include "ServerList.h" #include "FontManager.h" #include "FontSizer.h" #include "LocalFontFace.h" #include "HUDuiLabel.h" #include "OpenGLUtils.h" // // HUDuiServerInfo // HUDuiServerInfo::HUDuiServerInfo() : HUDuiControl() { readouts.push_back(new HUDuiLabel); // 0 readouts.push_back(new HUDuiLabel); // 1 readouts.push_back(new HUDuiLabel); // 2 readouts.push_back(new HUDuiLabel); // 3 readouts.push_back(new HUDuiLabel); // 4 readouts.push_back(new HUDuiLabel); // 5 readouts.push_back(new HUDuiLabel); // 6 readouts.push_back(new HUDuiLabel); // 7 max shots readouts.push_back(new HUDuiLabel); // 8 capture-the-flag/free-style/rabbit chase readouts.push_back(new HUDuiLabel); // 9 super-flags readouts.push_back(new HUDuiLabel); // 10 antidote-flag readouts.push_back(new HUDuiLabel); // 11 shaking time readouts.push_back(new HUDuiLabel); // 12 shaking wins readouts.push_back(new HUDuiLabel); // 13 jumping readouts.push_back(new HUDuiLabel); // 14 ricochet readouts.push_back(new HUDuiLabel); // 15 inertia readouts.push_back(new HUDuiLabel); // 16 time limit readouts.push_back(new HUDuiLabel); // 17 max team score readouts.push_back(new HUDuiLabel); // 18 max player score readouts.push_back(new HUDuiLabel); // 19 ping time readouts.push_back(new HUDuiLabel); // 20 cached status readouts.push_back(new HUDuiLabel); // 21 cached age HUDuiLabel* allPlayers = new HUDuiLabel; allPlayers->setString("Players"); playerLabels.push_back(allPlayers); HUDuiLabel* rogue = new HUDuiLabel; rogue->setString("Rogue"); playerLabels.push_back(rogue); HUDuiLabel* red = new HUDuiLabel; red->setString("Red"); playerLabels.push_back(red); HUDuiLabel* green = new HUDuiLabel; green->setString("Green"); playerLabels.push_back(green); HUDuiLabel* blue = new HUDuiLabel; blue->setString("Blue"); playerLabels.push_back(blue); HUDuiLabel* purple = new HUDuiLabel; purple->setString("Purple"); playerLabels.push_back(purple); HUDuiLabel* observers = new HUDuiLabel; observers->setString("Observers"); playerLabels.push_back(observers); } HUDuiServerInfo::~HUDuiServerInfo() { // Do nothing } void HUDuiServerInfo::setServerItem(ServerItem* item) { if (item == NULL) serverKey = ""; else serverKey = item->getServerKey(); } void HUDuiServerInfo::setSize(float width, float height) { HUDuiControl::setSize(width, height); resize(); } void HUDuiServerInfo::setFontSize(float size) { HUDuiControl::setFontSize(size); resize(); } void HUDuiServerInfo::setFontFace(const LocalFontFace* face) { HUDuiControl::setFontFace(face); resize(); } void HUDuiServerInfo::setPosition(float x, float y) { HUDuiControl::setPosition(x, y); resize(); } void HUDuiServerInfo::resize() { FontManager &fm = FontManager::instance(); FontSizer fs = FontSizer(getWidth(), getHeight()); // reposition server readouts float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize"); float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize); const float y0 = getY() + getHeight() - itemHeight - itemHeight/2; float y = y0; float x = getX() + itemHeight; fs.setMin(10, 10); for (size_t i=0; i<readouts.size(); i++) { if ((i + 1) % 7 == 1) { x = (0.125f + 0.25f * (float)(i / 7)) * (float)getWidth(); y = y0; } HUDuiLabel* readout = readouts[i]; readout->setFontSize(fontSize); readout->setFontFace(getFontFace()); y -= 1.0f * itemHeight; readout->setPosition(x, y); } // Was this supposed to be used somewhere? // float spacer = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "X"); x = (0.125f + 0.25f * (float)(1 / 7)) * (float)getWidth(); y = y0; for (size_t i=0; i<playerLabels.size(); i++) { HUDuiLabel* _label = playerLabels[i]; _label->setFontSize(fontSize); _label->setFontFace(getFontFace()); y -= 1.0f * itemHeight; _label->setPosition(x, y);} } void HUDuiServerInfo::fillReadouts() { ServerItem* itemPointer = ServerList::instance().lookupServer(serverKey); if (itemPointer == NULL) return; const ServerItem& item = *itemPointer; const PingPacket& ping = item.ping; // update server readouts char buf[60]; std::vector<HUDuiLabel*>& listHUD = readouts; //const uint8_t maxes [] = { ping.maxPlayers, ping.rogueMax, ping.redMax, ping.greenMax, // ping.blueMax, ping.purpleMax, ping.observerMax }; // if this is a cached item set the player counts to "?/max count" if (item.cached && item.getPlayerCount() == 0) { //for (int i = 1; i <=7; i ++) { // sprintf(buf, "?/%d", maxes[i-1]); // (listHUD[i])->setLabel(buf); //} } else { // not an old item, set players #s to info we have sprintf(buf, "%d/%d", ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount, ping.maxPlayers); (listHUD[0])->setLabel(buf); if (ping.rogueMax == 0) buf[0]=0; else if (ping.rogueMax >= ping.maxPlayers) sprintf(buf, "%d", ping.rogueCount); else sprintf(buf, "%d/%d", ping.rogueCount, ping.rogueMax); (listHUD[1])->setLabel(buf); if (ping.redMax == 0) buf[0]=0; else if (ping.redMax >= ping.maxPlayers) sprintf(buf, "%d", ping.redCount); else sprintf(buf, "%d/%d", ping.redCount, ping.redMax); (listHUD[2])->setLabel(buf); if (ping.greenMax == 0) buf[0]=0; else if (ping.greenMax >= ping.maxPlayers) sprintf(buf, "%d", ping.greenCount); else sprintf(buf, "%d/%d", ping.greenCount, ping.greenMax); (listHUD[3])->setLabel(buf); if (ping.blueMax == 0) buf[0]=0; else if (ping.blueMax >= ping.maxPlayers) sprintf(buf, "%d", ping.blueCount); else sprintf(buf, "%d/%d", ping.blueCount, ping.blueMax); (listHUD[4])->setLabel(buf); if (ping.purpleMax == 0) buf[0]=0; else if (ping.purpleMax >= ping.maxPlayers) sprintf(buf, "%d", ping.purpleCount); else sprintf(buf, "%d/%d", ping.purpleCount, ping.purpleMax); (listHUD[5])->setLabel(buf); if (ping.observerMax == 0) buf[0]=0; else if (ping.observerMax >= ping.maxPlayers) sprintf(buf, "%d", ping.observerCount); else sprintf(buf, "%d/%d", ping.observerCount, ping.observerMax); (listHUD[6])->setLabel(buf); } std::vector<std::string> args; sprintf(buf, "%d", ping.maxShots); args.push_back(buf); if (ping.maxShots == 1) (listHUD[7])->setString("{1} Shot", &args ); else (listHUD[7])->setString("{1} Shots", &args ); if (ping.gameType == ClassicCTF) (listHUD[8])->setString("Classic Capture-the-Flag"); else if (ping.gameType == RabbitChase) (listHUD[8])->setString("Rabbit Chase"); else if (ping.gameType == OpenFFA) (listHUD[8])->setString("Open (Teamless) Free-For-All"); else (listHUD[8])->setString("Team Free-For-All"); if (ping.gameOptions & SuperFlagGameStyle) (listHUD[9])->setString("Super Flags"); else (listHUD[9])->setString(""); if (ping.gameOptions & AntidoteGameStyle) (listHUD[10])->setString("Antidote Flags"); else (listHUD[10])->setString(""); if ((ping.gameOptions & ShakableGameStyle) && ping.shakeTimeout != 0) { std::vector<std::string> dropArgs; sprintf(buf, "%.1f", 0.1f * float(ping.shakeTimeout)); dropArgs.push_back(buf); if (ping.shakeWins == 1) (listHUD[11])->setString("{1} sec To Drop Bad Flag", &dropArgs); else (listHUD[11])->setString("{1} secs To Drop Bad Flag", &dropArgs); } else { (listHUD[11])->setString(""); } if ((ping.gameOptions & ShakableGameStyle) && ping.shakeWins != 0) { std::vector<std::string> dropArgs; sprintf(buf, "%d", ping.shakeWins); dropArgs.push_back(buf); dropArgs.push_back(ping.shakeWins == 1 ? "" : "s"); if (ping.shakeWins == 1) (listHUD[12])->setString("{1} Win Drops Bad Flag", &dropArgs); else (listHUD[12])->setString("{1} Wins Drops Bad Flag", &dropArgs); } else { (listHUD[12])->setString(""); } if (ping.gameOptions & JumpingGameStyle) (listHUD[13])->setString("Jumping"); else (listHUD[13])->setString(""); if (ping.gameOptions & RicochetGameStyle) (listHUD[14])->setString("Ricochet"); else (listHUD[14])->setString(""); if (ping.gameOptions & HandicapGameStyle) (listHUD[15])->setString("Handicap"); else (listHUD[15])->setString(""); if (ping.maxTime != 0) { std::vector<std::string> pingArgs; if (ping.maxTime >= 3600) sprintf(buf, "%d:%02d:%02d", ping.maxTime / 3600, (ping.maxTime / 60) % 60, ping.maxTime % 60); else if (ping.maxTime >= 60) sprintf(buf, "%d:%02d", ping.maxTime / 60, ping.maxTime % 60); else sprintf(buf, "0:%02d", ping.maxTime); pingArgs.push_back(buf); (listHUD[16])->setString("Time limit: {1}", &pingArgs); } else { (listHUD[16])->setString(""); } if (ping.maxTeamScore != 0) { std::vector<std::string> scoreArgs; sprintf(buf, "%d", ping.maxTeamScore); scoreArgs.push_back(buf); (listHUD[17])->setString("Max team score: {1}", &scoreArgs); } else { (listHUD[17])->setString(""); } if (ping.maxPlayerScore != 0) { std::vector<std::string> scoreArgs; sprintf(buf, "%d", ping.maxPlayerScore); scoreArgs.push_back(buf); (listHUD[18])->setString("Max player score: {1}", &scoreArgs); } else { (listHUD[18])->setString(""); } if (ping.pingTime > 0) { std::vector<std::string> pingArgs; sprintf(buf, "%dms", ping.pingTime); // What's the matter with a strstream. Come on! pingArgs.push_back(buf); // So last decade ((HUDuiLabel*)listHUD[19])->setString("Ping: {1}", &pingArgs); } else { ((HUDuiLabel*)listHUD[19])->setString(""); } if (item.cached) { (listHUD[20])->setString("Cached"); (listHUD[21])->setString(item.getAgeString()); } else { (listHUD[20])->setString(""); (listHUD[21])->setString(""); } } void HUDuiServerInfo::doRender() { if (getFontFace() < 0) { return; } FontManager &fm = FontManager::instance(); FontSizer fs = FontSizer(getWidth(), getHeight()); float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize"); float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize); float titleWidth = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "Server Information"); fm.drawString(getX() + (getWidth()/2) - (titleWidth/2), getY() + getHeight() - itemHeight, 0, getFontFace()->getFMFace(), fontSize, "Server Information"); float color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; glColor4fv(color); glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight(), -0.5f); glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight() - itemHeight - itemHeight/2, -0.5f); if (serverKey == "") return; fillReadouts(); for (std::vector<HUDuiLabel*>::iterator itr = readouts.begin(); itr != readouts.end(); ++itr) (*itr)->render(); for (std::vector<HUDuiLabel*>::iterator itr = playerLabels.begin(); itr != playerLabels.end(); ++itr) (*itr)->render(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Whitespace<commit_after>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // interface headers #include "HUDuiServerInfo.h" #include "playing.h" #include "ServerList.h" #include "FontManager.h" #include "FontSizer.h" #include "LocalFontFace.h" #include "HUDuiLabel.h" #include "OpenGLUtils.h" // // HUDuiServerInfo // HUDuiServerInfo::HUDuiServerInfo() : HUDuiControl() { readouts.push_back(new HUDuiLabel); // 0 readouts.push_back(new HUDuiLabel); // 1 readouts.push_back(new HUDuiLabel); // 2 readouts.push_back(new HUDuiLabel); // 3 readouts.push_back(new HUDuiLabel); // 4 readouts.push_back(new HUDuiLabel); // 5 readouts.push_back(new HUDuiLabel); // 6 readouts.push_back(new HUDuiLabel); // 7 max shots readouts.push_back(new HUDuiLabel); // 8 capture-the-flag/free-style/rabbit chase readouts.push_back(new HUDuiLabel); // 9 super-flags readouts.push_back(new HUDuiLabel); // 10 antidote-flag readouts.push_back(new HUDuiLabel); // 11 shaking time readouts.push_back(new HUDuiLabel); // 12 shaking wins readouts.push_back(new HUDuiLabel); // 13 jumping readouts.push_back(new HUDuiLabel); // 14 ricochet readouts.push_back(new HUDuiLabel); // 15 inertia readouts.push_back(new HUDuiLabel); // 16 time limit readouts.push_back(new HUDuiLabel); // 17 max team score readouts.push_back(new HUDuiLabel); // 18 max player score readouts.push_back(new HUDuiLabel); // 19 ping time readouts.push_back(new HUDuiLabel); // 20 cached status readouts.push_back(new HUDuiLabel); // 21 cached age HUDuiLabel* allPlayers = new HUDuiLabel; allPlayers->setString("Players"); playerLabels.push_back(allPlayers); HUDuiLabel* rogue = new HUDuiLabel; rogue->setString("Rogue"); playerLabels.push_back(rogue); HUDuiLabel* red = new HUDuiLabel; red->setString("Red"); playerLabels.push_back(red); HUDuiLabel* green = new HUDuiLabel; green->setString("Green"); playerLabels.push_back(green); HUDuiLabel* blue = new HUDuiLabel; blue->setString("Blue"); playerLabels.push_back(blue); HUDuiLabel* purple = new HUDuiLabel; purple->setString("Purple"); playerLabels.push_back(purple); HUDuiLabel* observers = new HUDuiLabel; observers->setString("Observers"); playerLabels.push_back(observers); } HUDuiServerInfo::~HUDuiServerInfo() { // Do nothing } void HUDuiServerInfo::setServerItem(ServerItem* item) { if (item == NULL) serverKey = ""; else serverKey = item->getServerKey(); } void HUDuiServerInfo::setSize(float width, float height) { HUDuiControl::setSize(width, height); resize(); } void HUDuiServerInfo::setFontSize(float size) { HUDuiControl::setFontSize(size); resize(); } void HUDuiServerInfo::setFontFace(const LocalFontFace* face) { HUDuiControl::setFontFace(face); resize(); } void HUDuiServerInfo::setPosition(float x, float y) { HUDuiControl::setPosition(x, y); resize(); } void HUDuiServerInfo::resize() { FontManager &fm = FontManager::instance(); FontSizer fs = FontSizer(getWidth(), getHeight()); // reposition server readouts float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize"); float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize); const float y0 = getY() + getHeight() - itemHeight - itemHeight/2; float y = y0; float x = getX() + itemHeight; fs.setMin(10, 10); for (size_t i=0; i<readouts.size(); i++) { if ((i + 1) % 7 == 1) { x = (0.125f + 0.25f * (float)(i / 7)) * (float)getWidth(); y = y0; } HUDuiLabel* readout = readouts[i]; readout->setFontSize(fontSize); readout->setFontFace(getFontFace()); y -= 1.0f * itemHeight; readout->setPosition(x, y); } // Was this supposed to be used somewhere? // float spacer = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "X"); x = (0.125f + 0.25f * (float)(1 / 7)) * (float)getWidth(); y = y0; for (size_t i=0; i<playerLabels.size(); i++) { HUDuiLabel* _label = playerLabels[i]; _label->setFontSize(fontSize); _label->setFontFace(getFontFace()); y -= 1.0f * itemHeight; _label->setPosition(x, y); } } void HUDuiServerInfo::fillReadouts() { ServerItem* itemPointer = ServerList::instance().lookupServer(serverKey); if (itemPointer == NULL) return; const ServerItem& item = *itemPointer; const PingPacket& ping = item.ping; // update server readouts char buf[60]; std::vector<HUDuiLabel*>& listHUD = readouts; //const uint8_t maxes [] = { ping.maxPlayers, ping.rogueMax, ping.redMax, ping.greenMax, // ping.blueMax, ping.purpleMax, ping.observerMax }; // if this is a cached item set the player counts to "?/max count" if (item.cached && item.getPlayerCount() == 0) { //for (int i = 1; i <=7; i ++) { // sprintf(buf, "?/%d", maxes[i-1]); // (listHUD[i])->setLabel(buf); //} } else { // not an old item, set players #s to info we have sprintf(buf, "%d/%d", ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount, ping.maxPlayers); (listHUD[0])->setLabel(buf); if (ping.rogueMax == 0) buf[0]=0; else if (ping.rogueMax >= ping.maxPlayers) sprintf(buf, "%d", ping.rogueCount); else sprintf(buf, "%d/%d", ping.rogueCount, ping.rogueMax); (listHUD[1])->setLabel(buf); if (ping.redMax == 0) buf[0]=0; else if (ping.redMax >= ping.maxPlayers) sprintf(buf, "%d", ping.redCount); else sprintf(buf, "%d/%d", ping.redCount, ping.redMax); (listHUD[2])->setLabel(buf); if (ping.greenMax == 0) buf[0]=0; else if (ping.greenMax >= ping.maxPlayers) sprintf(buf, "%d", ping.greenCount); else sprintf(buf, "%d/%d", ping.greenCount, ping.greenMax); (listHUD[3])->setLabel(buf); if (ping.blueMax == 0) buf[0]=0; else if (ping.blueMax >= ping.maxPlayers) sprintf(buf, "%d", ping.blueCount); else sprintf(buf, "%d/%d", ping.blueCount, ping.blueMax); (listHUD[4])->setLabel(buf); if (ping.purpleMax == 0) buf[0]=0; else if (ping.purpleMax >= ping.maxPlayers) sprintf(buf, "%d", ping.purpleCount); else sprintf(buf, "%d/%d", ping.purpleCount, ping.purpleMax); (listHUD[5])->setLabel(buf); if (ping.observerMax == 0) buf[0]=0; else if (ping.observerMax >= ping.maxPlayers) sprintf(buf, "%d", ping.observerCount); else sprintf(buf, "%d/%d", ping.observerCount, ping.observerMax); (listHUD[6])->setLabel(buf); } std::vector<std::string> args; sprintf(buf, "%d", ping.maxShots); args.push_back(buf); if (ping.maxShots == 1) (listHUD[7])->setString("{1} Shot", &args ); else (listHUD[7])->setString("{1} Shots", &args ); if (ping.gameType == ClassicCTF) (listHUD[8])->setString("Classic Capture-the-Flag"); else if (ping.gameType == RabbitChase) (listHUD[8])->setString("Rabbit Chase"); else if (ping.gameType == OpenFFA) (listHUD[8])->setString("Open (Teamless) Free-For-All"); else (listHUD[8])->setString("Team Free-For-All"); if (ping.gameOptions & SuperFlagGameStyle) (listHUD[9])->setString("Super Flags"); else (listHUD[9])->setString(""); if (ping.gameOptions & AntidoteGameStyle) (listHUD[10])->setString("Antidote Flags"); else (listHUD[10])->setString(""); if ((ping.gameOptions & ShakableGameStyle) && ping.shakeTimeout != 0) { std::vector<std::string> dropArgs; sprintf(buf, "%.1f", 0.1f * float(ping.shakeTimeout)); dropArgs.push_back(buf); if (ping.shakeWins == 1) (listHUD[11])->setString("{1} sec To Drop Bad Flag", &dropArgs); else (listHUD[11])->setString("{1} secs To Drop Bad Flag", &dropArgs); } else { (listHUD[11])->setString(""); } if ((ping.gameOptions & ShakableGameStyle) && ping.shakeWins != 0) { std::vector<std::string> dropArgs; sprintf(buf, "%d", ping.shakeWins); dropArgs.push_back(buf); dropArgs.push_back(ping.shakeWins == 1 ? "" : "s"); if (ping.shakeWins == 1) (listHUD[12])->setString("{1} Win Drops Bad Flag", &dropArgs); else (listHUD[12])->setString("{1} Wins Drops Bad Flag", &dropArgs); } else { (listHUD[12])->setString(""); } if (ping.gameOptions & JumpingGameStyle) (listHUD[13])->setString("Jumping"); else (listHUD[13])->setString(""); if (ping.gameOptions & RicochetGameStyle) (listHUD[14])->setString("Ricochet"); else (listHUD[14])->setString(""); if (ping.gameOptions & HandicapGameStyle) (listHUD[15])->setString("Handicap"); else (listHUD[15])->setString(""); if (ping.maxTime != 0) { std::vector<std::string> pingArgs; if (ping.maxTime >= 3600) sprintf(buf, "%d:%02d:%02d", ping.maxTime / 3600, (ping.maxTime / 60) % 60, ping.maxTime % 60); else if (ping.maxTime >= 60) sprintf(buf, "%d:%02d", ping.maxTime / 60, ping.maxTime % 60); else sprintf(buf, "0:%02d", ping.maxTime); pingArgs.push_back(buf); (listHUD[16])->setString("Time limit: {1}", &pingArgs); } else { (listHUD[16])->setString(""); } if (ping.maxTeamScore != 0) { std::vector<std::string> scoreArgs; sprintf(buf, "%d", ping.maxTeamScore); scoreArgs.push_back(buf); (listHUD[17])->setString("Max team score: {1}", &scoreArgs); } else { (listHUD[17])->setString(""); } if (ping.maxPlayerScore != 0) { std::vector<std::string> scoreArgs; sprintf(buf, "%d", ping.maxPlayerScore); scoreArgs.push_back(buf); (listHUD[18])->setString("Max player score: {1}", &scoreArgs); } else { (listHUD[18])->setString(""); } if (ping.pingTime > 0) { std::vector<std::string> pingArgs; sprintf(buf, "%dms", ping.pingTime); // What's the matter with a strstream. Come on! pingArgs.push_back(buf); // So last decade ((HUDuiLabel*)listHUD[19])->setString("Ping: {1}", &pingArgs); } else { ((HUDuiLabel*)listHUD[19])->setString(""); } if (item.cached) { (listHUD[20])->setString("Cached"); (listHUD[21])->setString(item.getAgeString()); } else { (listHUD[20])->setString(""); (listHUD[21])->setString(""); } } void HUDuiServerInfo::doRender() { if (getFontFace() < 0) { return; } FontManager &fm = FontManager::instance(); FontSizer fs = FontSizer(getWidth(), getHeight()); float fontSize = fs.getFontSize(getFontFace()->getFMFace(), "alertFontSize"); float itemHeight = fm.getStringHeight(getFontFace()->getFMFace(), fontSize); float titleWidth = fm.getStringWidth(getFontFace()->getFMFace(), fontSize, "Server Information"); fm.drawString(getX() + (getWidth()/2) - (titleWidth/2), getY() + getHeight() - itemHeight, 0, getFontFace()->getFMFace(), fontSize, "Server Information"); float color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; glColor4fv(color); glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight(), -0.5f); glOutlineBoxHV(1.0f, getX(), getY(), getX() + getWidth(), getY() + getHeight() - itemHeight - itemHeight/2, -0.5f); if (serverKey == "") return; fillReadouts(); for (std::vector<HUDuiLabel*>::iterator itr = readouts.begin(); itr != readouts.end(); ++itr) (*itr)->render(); for (std::vector<HUDuiLabel*>::iterator itr = playerLabels.begin(); itr != playerLabels.end(); ++itr) (*itr)->render(); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before><commit_msg>Change to generate BCE particles from ANCF cable elements faster<commit_after><|endoftext|>
<commit_before>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #ifdef ARCUS #include <Arcus/Error.h> //To process error codes. #include "Listener.h" #include "../utils/logoutput.h" namespace cura { void Listener::stateChanged(Arcus::SocketState::SocketState) { //Do nothing. } void Listener::messageReceived() { //Do nothing. } void Listener::error(const Arcus::Error& error) { if (error.getErrorCode() == Arcus::ErrorCode::Debug) { log("%s\n", error.toString().c_str()); } else { logError("%s\n", error.toString().c_str()); } } } //namespace cura #endif //ARCUS<commit_msg>Use getErrorMessage() instead of toString() in Arcus Listener CURA-5774<commit_after>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #ifdef ARCUS #include <Arcus/Error.h> //To process error codes. #include "Listener.h" #include "../utils/logoutput.h" namespace cura { void Listener::stateChanged(Arcus::SocketState::SocketState) { //Do nothing. } void Listener::messageReceived() { //Do nothing. } void Listener::error(const Arcus::Error& error) { if (error.getErrorCode() == Arcus::ErrorCode::Debug) { log("%s\n", error.getErrorMessage().c_str()); } else { logError("%s\n", error.getErrorMessage().c_str()); } } } //namespace cura #endif //ARCUS<|endoftext|>
<commit_before>#include "condor_common.h" #include "condor_debug.h" #include "condor_q.h" #include "condor_attributes.h" #include "condor_qmgr.h" // specify keyword lists; N.B. The order should follow from the category // enumerations in the .h file static const char *intKeywords[] = { ATTR_CLUSTER_ID, ATTR_PROC_ID, "Status", // ### This should be ATTR_JOB_STATUS "Universe" // ### This should be ATTR_JOB_UNIVERSE }; static const char *strKeywords[] = { ATTR_OWNER }; static const char *fltKeywords[] = { }; // scan function to walk the job queue extern "C" getJobAd (int, int); // need this global variable to hold information reqd by the scan function static ClassAdList *__list; static ClassAd *__query; CondorQ:: CondorQ () { query.setNumIntegerCats (CQ_INT_THRESHOLD); query.setNumStringCats (CQ_STR_THRESHOLD); query.setNumFloatCats (CQ_FLT_THRESHOLD); query.setIntegerKwList ((char **) intKeywords); query.setStringKwList ((char **) strKeywords); query.setFloatKwList ((char **) fltKeywords); } CondorQ:: ~CondorQ () { } int CondorQ:: add (CondorQIntCategories cat, int value) { return query.addInteger (cat, value); } int CondorQ:: add (CondorQStrCategories cat, char *value) { return query.addString (cat, value); } int CondorQ:: add (CondorQFltCategories cat, float value) { return query.addFloat (cat, value); } int CondorQ:: add (char *value) { return query.addCustom (value); } int CondorQ:: fetchQueue (ClassAdList &list, ClassAd *ad) { Qmgr_connection *qmgr; ClassAd filterAd; int result; char scheddString [32]; // make the query ad if ((result = query.makeQuery (filterAd)) != Q_OK) return result; // insert types into the query ad ### filterAd.SetMyTypeName ("Query"); filterAd.SetTargetTypeName ("Job"); // connect to the Q manager if (ad == 0) { // local case if (!(qmgr = ConnectQ (0))) return Q_SCHEDD_COMMUNICATION_ERROR; } else { // remote case to handle condor_globalq if (!ad->LookupString (ATTR_SCHEDD_IP_ADDR, scheddString)) return Q_NO_SCHEDD_IP_ADDR; if (!(qmgr = ConnectQ (scheddString))) return Q_SCHEDD_COMMUNICATION_ERROR; } // get the ads and filter them getAndFilterAds (filterAd, list); DisconnectQ (qmgr); return Q_OK; } int CondorQ:: fetchQueueFromHost (ClassAdList &list, char *host) { Qmgr_connection *qmgr; ClassAd filterAd; int result; char scheddString [32]; // make the query ad if ((result = query.makeQuery (filterAd)) != Q_OK) return result; // insert types into the query ad ### filterAd.SetMyTypeName ("Query"); filterAd.SetTargetTypeName ("Job"); // connect to the Q manager if (!(qmgr = ConnectQ (host))) return Q_SCHEDD_COMMUNICATION_ERROR; // get the ads and filter them getAndFilterAds (filterAd, list); DisconnectQ (qmgr); return Q_OK; } int CondorQ:: getAndFilterAds (ClassAd &ad, ClassAdList &list) { __list = &list; __query = &ad; WalkJobQueue (getJobAd); return Q_OK; } getJobAd(int cluster_id, int proc_id) { char buf[1000]; char buf2[1000]; int rval; ClassAd *new_ad = new ClassAd; // this code is largely Jim Pruyne's original qmgmt_test.c program --RR rval = FirstAttribute(cluster_id, proc_id, buf); while( rval >= 0) { rval = GetAttributeExpr(cluster_id, proc_id, buf, buf2); if (rval >= 0) { if (!new_ad->Insert (buf2)) { // failed to insert expr --- abort this ad delete new_ad; return 1; } rval = NextAttribute(cluster_id, proc_id, buf); } } // insert types for the ad ### Use from some canonical file? --RR new_ad->SetMyTypeName ("Job"); new_ad->SetTargetTypeName ("Machine"); // iff the job ad matches the query, insert it into the list if ((*new_ad) >= (*__query)) __list->Insert (new_ad); else delete new_ad; return 0; } /* queue printing routines moved here from proc_obj.C, which is being taken out of cplus_lib.a. -Jim B. */ /* Format a date expressed in "UNIX time" into "month/day hour:minute". */ static char * format_date( time_t date ) { static char buf[ 12 ]; struct tm *tm; tm = localtime( &date ); sprintf( buf, "%2d/%-2d %02d:%02d", (tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min ); return buf; } /* Format a time value which is encoded as seconds since the UNIX "epoch". We return a string in the format dd+hh:mm:ss, indicating days, hours, minutes, and seconds. The string is in static data space, and will be overwritten by the next call to this function. */ static char * format_time( int tot_secs ) { int days; int hours; int min; int secs; static char answer[25]; days = tot_secs / DAY; tot_secs %= DAY; hours = tot_secs / HOUR; tot_secs %= HOUR; min = tot_secs / MINUTE; secs = tot_secs % MINUTE; (void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs ); return answer; } /* Encode a status from a PROC structure as a single letter suited for printing. */ static char encode_status( int status ) { switch( status ) { case UNEXPANDED: return 'U'; case IDLE: return 'I'; case RUNNING: return 'R'; case COMPLETED: return 'C'; case REMOVED: return 'X'; default: return ' '; } } /* Print a line of data for the "short" display of a PROC structure. The "short" display is the one used by "condor_q". N.B. the columns used by this routine must match those defined by the short_header routine defined above. */ void short_print( int cluster, int proc, const char *owner, int date, int time, int status, int prio, int image_size, const char *cmd ) { printf( "%4d.%-3d %-14s %-11s %-12s %-2c %-3d %-4.1f %-18s\n", cluster, proc, owner, format_date(date), format_time(time), encode_status(status), prio, image_size/1024.0, cmd ); } <commit_msg>use ATTR_JOB_STATUS and ATTR_JOB_UNIVERSE<commit_after>#include "condor_common.h" #include "condor_debug.h" #include "condor_q.h" #include "condor_attributes.h" #include "condor_qmgr.h" // specify keyword lists; N.B. The order should follow from the category // enumerations in the .h file static const char *intKeywords[] = { ATTR_CLUSTER_ID, ATTR_PROC_ID, ATTR_JOB_STATUS, ATTR_JOB_UNIVERSE }; static const char *strKeywords[] = { ATTR_OWNER }; static const char *fltKeywords[] = { }; // scan function to walk the job queue extern "C" getJobAd (int, int); // need this global variable to hold information reqd by the scan function static ClassAdList *__list; static ClassAd *__query; CondorQ:: CondorQ () { query.setNumIntegerCats (CQ_INT_THRESHOLD); query.setNumStringCats (CQ_STR_THRESHOLD); query.setNumFloatCats (CQ_FLT_THRESHOLD); query.setIntegerKwList ((char **) intKeywords); query.setStringKwList ((char **) strKeywords); query.setFloatKwList ((char **) fltKeywords); } CondorQ:: ~CondorQ () { } int CondorQ:: add (CondorQIntCategories cat, int value) { return query.addInteger (cat, value); } int CondorQ:: add (CondorQStrCategories cat, char *value) { return query.addString (cat, value); } int CondorQ:: add (CondorQFltCategories cat, float value) { return query.addFloat (cat, value); } int CondorQ:: add (char *value) { return query.addCustom (value); } int CondorQ:: fetchQueue (ClassAdList &list, ClassAd *ad) { Qmgr_connection *qmgr; ClassAd filterAd; int result; char scheddString [32]; // make the query ad if ((result = query.makeQuery (filterAd)) != Q_OK) return result; // insert types into the query ad ### filterAd.SetMyTypeName ("Query"); filterAd.SetTargetTypeName ("Job"); // connect to the Q manager if (ad == 0) { // local case if (!(qmgr = ConnectQ (0))) return Q_SCHEDD_COMMUNICATION_ERROR; } else { // remote case to handle condor_globalq if (!ad->LookupString (ATTR_SCHEDD_IP_ADDR, scheddString)) return Q_NO_SCHEDD_IP_ADDR; if (!(qmgr = ConnectQ (scheddString))) return Q_SCHEDD_COMMUNICATION_ERROR; } // get the ads and filter them getAndFilterAds (filterAd, list); DisconnectQ (qmgr); return Q_OK; } int CondorQ:: fetchQueueFromHost (ClassAdList &list, char *host) { Qmgr_connection *qmgr; ClassAd filterAd; int result; char scheddString [32]; // make the query ad if ((result = query.makeQuery (filterAd)) != Q_OK) return result; // insert types into the query ad ### filterAd.SetMyTypeName ("Query"); filterAd.SetTargetTypeName ("Job"); // connect to the Q manager if (!(qmgr = ConnectQ (host))) return Q_SCHEDD_COMMUNICATION_ERROR; // get the ads and filter them getAndFilterAds (filterAd, list); DisconnectQ (qmgr); return Q_OK; } int CondorQ:: getAndFilterAds (ClassAd &ad, ClassAdList &list) { __list = &list; __query = &ad; WalkJobQueue (getJobAd); return Q_OK; } getJobAd(int cluster_id, int proc_id) { char buf[1000]; char buf2[1000]; int rval; ClassAd *new_ad = new ClassAd; // this code is largely Jim Pruyne's original qmgmt_test.c program --RR rval = FirstAttribute(cluster_id, proc_id, buf); while( rval >= 0) { rval = GetAttributeExpr(cluster_id, proc_id, buf, buf2); if (rval >= 0) { if (!new_ad->Insert (buf2)) { // failed to insert expr --- abort this ad delete new_ad; return 1; } rval = NextAttribute(cluster_id, proc_id, buf); } } // insert types for the ad ### Use from some canonical file? --RR new_ad->SetMyTypeName ("Job"); new_ad->SetTargetTypeName ("Machine"); // iff the job ad matches the query, insert it into the list if ((*new_ad) >= (*__query)) __list->Insert (new_ad); else delete new_ad; return 0; } /* queue printing routines moved here from proc_obj.C, which is being taken out of cplus_lib.a. -Jim B. */ /* Format a date expressed in "UNIX time" into "month/day hour:minute". */ static char * format_date( time_t date ) { static char buf[ 12 ]; struct tm *tm; tm = localtime( &date ); sprintf( buf, "%2d/%-2d %02d:%02d", (tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min ); return buf; } /* Format a time value which is encoded as seconds since the UNIX "epoch". We return a string in the format dd+hh:mm:ss, indicating days, hours, minutes, and seconds. The string is in static data space, and will be overwritten by the next call to this function. */ static char * format_time( int tot_secs ) { int days; int hours; int min; int secs; static char answer[25]; days = tot_secs / DAY; tot_secs %= DAY; hours = tot_secs / HOUR; tot_secs %= HOUR; min = tot_secs / MINUTE; secs = tot_secs % MINUTE; (void)sprintf( answer, "%3d+%02d:%02d:%02d", days, hours, min, secs ); return answer; } /* Encode a status from a PROC structure as a single letter suited for printing. */ static char encode_status( int status ) { switch( status ) { case UNEXPANDED: return 'U'; case IDLE: return 'I'; case RUNNING: return 'R'; case COMPLETED: return 'C'; case REMOVED: return 'X'; default: return ' '; } } /* Print a line of data for the "short" display of a PROC structure. The "short" display is the one used by "condor_q". N.B. the columns used by this routine must match those defined by the short_header routine defined above. */ void short_print( int cluster, int proc, const char *owner, int date, int time, int status, int prio, int image_size, const char *cmd ) { printf( "%4d.%-3d %-14s %-11s %-12s %-2c %-3d %-4.1f %-18s\n", cluster, proc, owner, format_date(date), format_time(time), encode_status(status), prio, image_size/1024.0, cmd ); } <|endoftext|>
<commit_before>/* * ArrayTest.cpp * * Created on: Feb 28, 2015 * Author: hugo */ #include <cmath> #include <ctime> #include <iostream> #include "../core/malgorithm.hpp" #include "../core/matrix.hpp" #include "../core/matrixworker.hpp" #include "../core/operator.hpp" #include "../core/primitivevector.hpp" #include "../core/type.hpp" #include "../core/vector.hpp" #include "../log/easylogging++.h" using namespace std; using namespace mflash; INITIALIZE_EASYLOGGINGPP struct PairShort{ short data1; short data2; }; template <class V = PairShort, class E = EmptyType> class SpMV2 : public MAlgorithm<V,E>{ public: inline void initialize(MatrixWorker<PairShort, E> &worker, Element<PairShort> &out_element){ out_element.value->data1 = 0; out_element.value->data2 = 1; } inline void gather(MatrixWorker<PairShort, E> &worker, Element<PairShort> &in_element, Element<PairShort> &out_element, E &edge_data){ } inline void sum(Element<PairShort> &accumulator1, Element<PairShort> &accumulator2, Element<PairShort> &out_accumulator){} inline void apply(MatrixWorker<PairShort, E> &worker, Element<V> &out_element) {} inline bool isInitialized(){ return true; } inline bool isApplied(){ return false; } }; template <class V, class E> class SpMV : public MAlgorithm<V,E>{ public: inline void initialize(MatrixWorker<V, E> &worker, Element<V> &out_element){ *(out_element.value) = 0; } inline void gather(MatrixWorker<V, E> &worker, Element<V> &in_element, Element<V> &out_element, E &edge_data){ *(out_element.value) += *(in_element.value); } inline void sum(Element<V> &accumulator1, Element<V> &accumulator2, Element<V> &out_accumulator){} inline void apply(MatrixWorker<V, E> &worker, Element<V> &out_element) {} inline bool isInitialized(){ return true; } inline bool isApplied(){ return false; } }; class PrintOperator : public ZeroOperator<float>{ public: void apply(Element<float> &element){ cout<<"["<<element.id<<"]="<<*(element.value)<<endl; } }; class CustoOperator : public ZeroOperator<float>{ public: void apply(Element<float> &element){ *(element.value) = 1; } }; class CustomOperator2 : public BinaryOperator<float>{ public: void apply(Element<float> &v1, Element<float> &v2, Element<float> &out){ *(out.value) = *(v1.value) + 2 * *(v2.value); } }; class CustomOperator3 : public UnaryReducer<float>{ public: void initialize(float &v1){ v1 = 0; } void sum(float &v1, float &v2 , float &out){ out = v1 + v2; } void apply(Element<float> &v1, Element<float> &out){ *(out.value) = *(v1.value) * 2.001; } }; class CustomOperator4 : public BinaryReducer<float>{ public: void initialize(float &v1){ v1 = 0; } void sum(float &v1, float &v2 , float &out){ out = v1 + v2; } void apply(Element<float> &v1, Element<float> &v2, Element<float> &out){ *(out.value) = *(v1.value) * 2; } }; int main(){ int64 size = 97; int64 bsize = 10; //float value; CustoOperator op;// = new CustoOperator; CustomOperator2 op2; CustomOperator3 op3; CustomOperator4 op4; PrintOperator prindst ; PrimitiveVector<float> pvector("/tmp/v31", size, bsize); PrimitiveVector<float> pvector2("/tmp/v42", size, bsize); PrimitiveVector<float> pout("/tmp/ou1t", size, bsize); pvector.fill(3); pvector.operate(prindst); //Vector<float>::operate(prindst, pvector, 0, new Vector<float>*[0]{}); pvector2.fill(2); pvector2.operate(prindst); //Vector<float>::operate(prindst, pvector2, 0, new Vector<float>*[0]{}); //PrimitiveVector<float> *pvectors ;//new PrimitiveVector<float>[2]{pvector, pvector2}; float constants [] = {5,6}; pout.linear_combination(2, constants, new PrimitiveVector<float>*[3]{&pvector, &pvector2}); //Vector<float>::operate(prindst, pout, 0, new Vector<float>*[0]{}); pout.operate(prindst); cout<< "Linear combination = "<< pout.pnorm(1) << endl; pvector.fill_random(); cout<< pvector.pnorm(2) << endl; PrimitiveVector<float> t = pvector.transpose(); cout<< pvector.multiply(t) << endl; cout<< pow(pvector.pnorm(2),2) << endl; pvector.multiply((float)(1/pvector.pnorm(2))); cout<< pvector.pnorm(2) << endl; size = 1413511394; bsize = 939524096; SpMV<float, EmptyType> spmv; Vector<float> *vector = new Vector<float>("/hugo/datasets/yahoo/v1", size, bsize); Vector<float> *out = new Vector<float>("/hugo/datasets/yahoo/v2", size, bsize); //value = vector->operate(op, *vector, 0, new Vector<float>[0]{/**vector*/}); //exit(0); // value = vector->operate(op, *vector, 0, new Vector<float>[0]{/**vector*/}); //value = vector->operate(op3, *vector, 0, new Vector<float>[0]{/**vector*/}); //cout << value << endl; time_t timer1; time_t timer2; time(&timer1); Matrix<float, EmptyType> matrix ("/hugo/datasets/yahoo/yahoo.bin", size, false, bsize, Mode::UNSAFE); matrix.operate(spmv, *vector, *out); time(&timer2); time_t final = timer2 - timer1; cout<<"Time: "<< final << " seconds"; /* Array<float> *array = new Array<float>(size); Array<float>::operate(op, *array); value = Array<float>::operate(op3, *array); cout << value << endl; value = Array<float>::operate(op4, *array, *array); cout << value << endl; Array<float>::operate(op2, *array, *array, *array); cout<< *(array->get_element(size-1)) << endl;*/ } <commit_msg>Test for SpMV using PrimitiveMatrix<commit_after>/* * ArrayTest.cpp * * Created on: Feb 28, 2015 * Author: hugo */ #include <cmath> #include <ctime> #include <iostream> #include "../core/malgorithm.hpp" #include "../core/matrixworker.hpp" #include "../core/operator.hpp" #include "../core/primitivematrix.hpp" #include "../core/primitivevector.hpp" #include "../core/type.hpp" #include "../core/vector.hpp" #include "../log/easylogging++.h" using namespace std; using namespace mflash; INITIALIZE_EASYLOGGINGPP struct PairShort{ short data1; short data2; }; template <class V = PairShort, class E = EmptyType> class SpMV2 : public MAlgorithm<V,E>{ public: inline void initialize(MatrixWorker<PairShort, E> &worker, Element<PairShort> &out_element){ out_element.value->data1 = 0; out_element.value->data2 = 1; } inline void gather(MatrixWorker<PairShort, E> &worker, Element<PairShort> &in_element, Element<PairShort> &out_element, E &edge_data){ } inline void sum(Element<PairShort> &accumulator1, Element<PairShort> &accumulator2, Element<PairShort> &out_accumulator){} inline void apply(MatrixWorker<PairShort, E> &worker, Element<V> &out_element) {} inline bool isInitialized(){ return true; } inline bool isApplied(){ return false; } }; template <class V, class E> class SpMV : public MAlgorithm<V,E>{ public: inline void initialize(MatrixWorker<V, E> &worker, Element<V> &out_element){ *(out_element.value) = 0; } inline void gather(MatrixWorker<V, E> &worker, Element<V> &in_element, Element<V> &out_element, E &edge_data){ *(out_element.value) += *(in_element.value); } inline void sum(Element<V> &accumulator1, Element<V> &accumulator2, Element<V> &out_accumulator){} inline void apply(MatrixWorker<V, E> &worker, Element<V> &out_element) {} inline bool isInitialized(){ return true; } inline bool isApplied(){ return false; } }; class PrintOperator : public ZeroOperator<float>{ public: void apply(Element<float> &element){ cout<<"["<<element.id<<"]="<<*(element.value)<<endl; } }; class CustoOperator : public ZeroOperator<float>{ public: void apply(Element<float> &element){ *(element.value) = 1; } }; class CustomOperator2 : public BinaryOperator<float>{ public: void apply(Element<float> &v1, Element<float> &v2, Element<float> &out){ *(out.value) = *(v1.value) + 2 * *(v2.value); } }; class CustomOperator3 : public UnaryReducer<float>{ public: void initialize(float &v1){ v1 = 0; } void sum(float &v1, float &v2 , float &out){ out = v1 + v2; } void apply(Element<float> &v1, Element<float> &out){ *(out.value) = *(v1.value) * 2.001; } }; class CustomOperator4 : public BinaryReducer<float>{ public: void initialize(float &v1){ v1 = 0; } void sum(float &v1, float &v2 , float &out){ out = v1 + v2; } void apply(Element<float> &v1, Element<float> &v2, Element<float> &out){ *(out.value) = *(v1.value) * 2; } }; int main(){ int64 size = 97; int64 bsize = 10; //float value; CustoOperator op;// = new CustoOperator; CustomOperator2 op2; CustomOperator3 op3; CustomOperator4 op4; PrintOperator prindst ; PrimitiveVector<float> pvector("/tmp/v31", size, bsize); PrimitiveVector<float> pvector2("/tmp/v42", size, bsize); PrimitiveVector<float> pout("/tmp/ou1t", size, bsize); pvector.fill(3); pvector.operate(prindst); //Vector<float>::operate(prindst, pvector, 0, new Vector<float>*[0]{}); pvector2.fill(2); pvector2.operate(prindst); //Vector<float>::operate(prindst, pvector2, 0, new Vector<float>*[0]{}); //PrimitiveVector<float> *pvectors ;//new PrimitiveVector<float>[2]{pvector, pvector2}; float constants [] = {5,6}; pout.linear_combination(2, constants, new PrimitiveVector<float>*[3]{&pvector, &pvector2}); //Vector<float>::operate(prindst, pout, 0, new Vector<float>*[0]{}); pout.operate(prindst); cout<< "Linear combination = "<< pout.pnorm(1) << endl; pvector.fill_random(); cout<< pvector.pnorm(2) << endl; PrimitiveVector<float> t = pvector.transpose(); cout<< pvector.multiply(t) << endl; cout<< pow(pvector.pnorm(2),2) << endl; pvector.multiply((float)(1/pvector.pnorm(2))); cout<< pvector.pnorm(2) << endl; size = 1413511394; bsize = 939524096; SpMV<float, EmptyType> spmv; PrimitiveVector<float> *vector = new PrimitiveVector<float>("/hugo/datasets/yahoo/v1", size, bsize); PrimitiveVector<float> *out = new PrimitiveVector<float>("/hugo/datasets/yahoo/v2", size, bsize); vector->fill(1); //value = vector->operate(op, *vector, 0, new Vector<float>[0]{/**vector*/}); //exit(0); // value = vector->operate(op, *vector, 0, new Vector<float>[0]{/**vector*/}); //value = vector->operate(op3, *vector, 0, new Vector<float>[0]{/**vector*/}); //cout << value << endl; time_t timer1; time_t timer2; time(&timer1); PrimitiveMatrix< float, EmptyType> matrix ("/hugo/datasets/yahoo/yahoo.bin", size, false, bsize, Mode::UNSAFE); matrix.multiply(*vector, *out); //matrix.operate(spmv, *vector, *out); time(&timer2); time_t final = timer2 - timer1; cout<<"Time: "<< final << " seconds"; time(&timer1); matrix.multiply(*vector, *out); //matrix.operate(spmv, *vector, *out); time(&timer2); final = timer2 - timer1; cout<<"Time: "<< final << " seconds"; /* Array<float> *array = new Array<float>(size); Array<float>::operate(op, *array); value = Array<float>::operate(op3, *array); cout << value << endl; value = Array<float>::operate(op4, *array, *array); cout << value << endl; Array<float>::operate(op2, *array, *array, *array); cout<< *(array->get_element(size-1)) << endl;*/ } <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/gpr/time_precise.h" #ifdef GPR_POSIX_TIME #include <stdlib.h> #include <time.h> #include <unistd.h> #ifdef __linux__ #include <sys/syscall.h> #endif #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> static struct timespec timespec_from_gpr(gpr_timespec gts) { struct timespec rv; if (sizeof(time_t) < sizeof(int64_t)) { /* fine to assert, as this is only used in gpr_sleep_until */ GPR_ASSERT(gts.tv_sec <= INT32_MAX && gts.tv_sec >= INT32_MIN); } rv.tv_sec = static_cast<time_t>(gts.tv_sec); rv.tv_nsec = gts.tv_nsec; return rv; } #if _POSIX_TIMERS > 0 || defined(__OpenBSD__) static gpr_timespec gpr_from_timespec(struct timespec ts, gpr_clock_type clock_type) { /* * timespec.tv_sec can have smaller size than gpr_timespec.tv_sec, * but we are only using this function to implement gpr_now * so there's no need to handle "infinity" values. */ gpr_timespec rv; rv.tv_sec = ts.tv_sec; rv.tv_nsec = static_cast<int32_t>(ts.tv_nsec); rv.clock_type = clock_type; return rv; } /** maps gpr_clock_type --> clockid_t for clock_gettime */ static const clockid_t clockid_for_gpr_clock[] = {CLOCK_MONOTONIC, CLOCK_REALTIME}; void gpr_time_init(void) { gpr_precise_clock_init(); } static gpr_timespec now_impl(gpr_clock_type clock_type) { struct timespec now; GPR_ASSERT(clock_type != GPR_TIMESPAN); if (clock_type == GPR_CLOCK_PRECISE) { gpr_timespec ret; gpr_precise_clock_now(&ret); return ret; } else { #if defined(GPR_BACKWARDS_COMPATIBILITY_MODE) && defined(__linux__) /* avoid ABI problems by invoking syscalls directly */ syscall(SYS_clock_gettime, clockid_for_gpr_clock[clock_type], &now); #else clock_gettime(clockid_for_gpr_clock[clock_type], &now); #endif return gpr_from_timespec(now, clock_type); } } #else /* For some reason Apple's OSes haven't implemented clock_gettime. */ #include <mach/mach.h> #include <mach/mach_time.h> #include <sys/time.h> static double g_time_scale; static uint64_t g_time_start; void gpr_time_init(void) { mach_timebase_info_data_t tb = {0, 1}; gpr_precise_clock_init(); mach_timebase_info(&tb); g_time_scale = tb.numer; g_time_scale /= tb.denom; g_time_start = mach_absolute_time(); } static gpr_timespec now_impl(gpr_clock_type clock) { gpr_timespec now; struct timeval now_tv; double now_dbl; now.clock_type = clock; switch (clock) { case GPR_CLOCK_REALTIME: gettimeofday(&now_tv, nullptr); now.tv_sec = now_tv.tv_sec; now.tv_nsec = now_tv.tv_usec * 1000; break; case GPR_CLOCK_MONOTONIC: now_dbl = ((double)(mach_absolute_time() - g_time_start)) * g_time_scale; now.tv_sec = (int64_t)(now_dbl * 1e-9); now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9); break; case GPR_CLOCK_PRECISE: gpr_precise_clock_now(&now); break; case GPR_TIMESPAN: abort(); } return now; } #endif gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl; #ifdef GPR_LOW_LEVEL_COUNTERS gpr_atm gpr_now_call_count; #endif gpr_timespec gpr_now(gpr_clock_type clock_type) { #ifdef GPR_LOW_LEVEL_COUNTERS __atomic_fetch_add(&gpr_now_call_count, 1, __ATOMIC_RELAXED); #endif // validate clock type GPR_ASSERT(clock_type == GPR_CLOCK_MONOTONIC || clock_type == GPR_CLOCK_REALTIME || clock_type == GPR_CLOCK_PRECISE); gpr_timespec ts = gpr_now_impl(clock_type); // tv_nsecs must be in the range [0, 1e9). GPR_ASSERT(ts.tv_nsec >= 0 && ts.tv_nsec < 1e9); return ts; } void gpr_sleep_until(gpr_timespec until) { gpr_timespec now; gpr_timespec delta; struct timespec delta_ts; int ns_result; for (;;) { /* We could simplify by using clock_nanosleep instead, but it might be * slightly less portable. */ now = gpr_now(until.clock_type); if (gpr_time_cmp(until, now) <= 0) { return; } delta = gpr_time_sub(until, now); delta_ts = timespec_from_gpr(delta); ns_result = nanosleep(&delta_ts, nullptr); if (ns_result == 0) { break; } } } #endif /* GPR_POSIX_TIME */ <commit_msg>Add guard to the tv_nsec field of gpr_now return value<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/gpr/time_precise.h" #ifdef GPR_POSIX_TIME #include <stdlib.h> #include <time.h> #include <unistd.h> #ifdef __linux__ #include <sys/syscall.h> #endif #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> static struct timespec timespec_from_gpr(gpr_timespec gts) { struct timespec rv; if (sizeof(time_t) < sizeof(int64_t)) { /* fine to assert, as this is only used in gpr_sleep_until */ GPR_ASSERT(gts.tv_sec <= INT32_MAX && gts.tv_sec >= INT32_MIN); } rv.tv_sec = static_cast<time_t>(gts.tv_sec); rv.tv_nsec = gts.tv_nsec; return rv; } #if _POSIX_TIMERS > 0 || defined(__OpenBSD__) static gpr_timespec gpr_from_timespec(struct timespec ts, gpr_clock_type clock_type) { /* * timespec.tv_sec can have smaller size than gpr_timespec.tv_sec, * but we are only using this function to implement gpr_now * so there's no need to handle "infinity" values. */ gpr_timespec rv; rv.tv_sec = ts.tv_sec; rv.tv_nsec = static_cast<int32_t>(ts.tv_nsec); rv.clock_type = clock_type; return rv; } /** maps gpr_clock_type --> clockid_t for clock_gettime */ static const clockid_t clockid_for_gpr_clock[] = {CLOCK_MONOTONIC, CLOCK_REALTIME}; void gpr_time_init(void) { gpr_precise_clock_init(); } static gpr_timespec now_impl(gpr_clock_type clock_type) { struct timespec now; GPR_ASSERT(clock_type != GPR_TIMESPAN); if (clock_type == GPR_CLOCK_PRECISE) { gpr_timespec ret; gpr_precise_clock_now(&ret); return ret; } else { #if defined(GPR_BACKWARDS_COMPATIBILITY_MODE) && defined(__linux__) /* avoid ABI problems by invoking syscalls directly */ syscall(SYS_clock_gettime, clockid_for_gpr_clock[clock_type], &now); #else clock_gettime(clockid_for_gpr_clock[clock_type], &now); #endif return gpr_from_timespec(now, clock_type); } } #else /* For some reason Apple's OSes haven't implemented clock_gettime. */ #include <mach/mach.h> #include <mach/mach_time.h> #include <sys/time.h> static double g_time_scale; static uint64_t g_time_start; void gpr_time_init(void) { mach_timebase_info_data_t tb = {0, 1}; gpr_precise_clock_init(); mach_timebase_info(&tb); g_time_scale = tb.numer; g_time_scale /= tb.denom; g_time_start = mach_absolute_time(); } static gpr_timespec now_impl(gpr_clock_type clock) { gpr_timespec now; struct timeval now_tv; double now_dbl; now.clock_type = clock; switch (clock) { case GPR_CLOCK_REALTIME: // gettimeofday(...) function may return with a value whose tv_usec is // greater than 1e6 on iOS The case is resolved with the guard at end of // this function. gettimeofday(&now_tv, nullptr); now.tv_sec = now_tv.tv_sec; now.tv_nsec = now_tv.tv_usec * 1000; break; case GPR_CLOCK_MONOTONIC: now_dbl = ((double)(mach_absolute_time() - g_time_start)) * g_time_scale; now.tv_sec = (int64_t)(now_dbl * 1e-9); now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9); break; case GPR_CLOCK_PRECISE: gpr_precise_clock_now(&now); break; case GPR_TIMESPAN: abort(); } // Guard the tv_nsec field in valid range for all clock types while (GPR_UNLIKELY(now.tv_nsec >= 1e9)) { now.tv_sec++; now.tv_nsec -= 1e9; } while (GPR_UNLIKELY(now.tv_nsec < 0)) { now.tv_sec--; now.tv_nsec += 1e9; } return now; } #endif gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl; #ifdef GPR_LOW_LEVEL_COUNTERS gpr_atm gpr_now_call_count; #endif gpr_timespec gpr_now(gpr_clock_type clock_type) { #ifdef GPR_LOW_LEVEL_COUNTERS __atomic_fetch_add(&gpr_now_call_count, 1, __ATOMIC_RELAXED); #endif // validate clock type GPR_ASSERT(clock_type == GPR_CLOCK_MONOTONIC || clock_type == GPR_CLOCK_REALTIME || clock_type == GPR_CLOCK_PRECISE); gpr_timespec ts = gpr_now_impl(clock_type); // tv_nsecs must be in the range [0, 1e9). GPR_ASSERT(ts.tv_nsec >= 0 && ts.tv_nsec < 1e9); return ts; } void gpr_sleep_until(gpr_timespec until) { gpr_timespec now; gpr_timespec delta; struct timespec delta_ts; int ns_result; for (;;) { /* We could simplify by using clock_nanosleep instead, but it might be * slightly less portable. */ now = gpr_now(until.clock_type); if (gpr_time_cmp(until, now) <= 0) { return; } delta = gpr_time_sub(until, now); delta_ts = timespec_from_gpr(delta); ns_result = nanosleep(&delta_ts, nullptr); if (ns_result == 0) { break; } } } #endif /* GPR_POSIX_TIME */ <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <testHelpers.hpp> #include <cmath> using std::string; using std::vector; using af::dim4; template<typename T> class Meanshift : public ::testing::Test { public: virtual void SetUp() {} }; typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes; TYPED_TEST_CASE(Meanshift, TestTypes); TYPED_TEST(Meanshift, InvalidArgs) { if (noDoubleTests<TypeParam>()) return; vector<TypeParam> in(100,1); af_array inArray = 0; af_array outArray = 0; af::dim4 dims = af::dim4(100,1,1,1); ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type)); ASSERT_EQ(AF_ERR_SIZE, af_meanshift(&outArray, inArray, 0.12f, 0.34f, 5, true)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); } template<typename T, bool isColor> void meanshiftTest(string pTestFile) { if (noDoubleTests<T>()) return; vector<dim4> inDims; vector<string> inFiles; vector<dim_type> outSizes; vector<string> outFiles; readImageTests(pTestFile, inDims, inFiles, outSizes, outFiles); size_t testCount = inDims.size(); for (size_t testId=0; testId<testCount; ++testId) { af_array inArray = 0; af_array outArray = 0; af_array goldArray= 0; dim_type nElems = 0; inFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); outFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); ASSERT_EQ(AF_SUCCESS, af_load_image(&inArray, inFiles[testId].c_str(), isColor)); ASSERT_EQ(AF_SUCCESS, af_load_image(&goldArray, outFiles[testId].c_str(), isColor)); ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems, goldArray)); ASSERT_EQ(AF_SUCCESS, af_meanshift(&outArray, inArray, 2.25f, 25.56f, 5, isColor)); T * outData = new T[nElems]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); T * goldData= new T[nElems]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)goldData, goldArray)); ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.07f)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(goldArray)); } } // create a list of types to be tested // FIXME: since af_load_image returns only f32 type arrays // only float, double data types test are enabled & passing // Note: compareArraysRMSD is handling upcasting while working // with two different type of types // #define IMAGE_TESTS(T) \ TEST(Meanshift, Grayscale_##T) \ { \ meanshiftTest<T, false>(string(TEST_DIR"/meanshift/gray.test")); \ } \ TEST(Meanshift, Color_##T) \ { \ meanshiftTest<T, true>(string(TEST_DIR"/meanshift/color.test")); \ } IMAGE_TESTS(float ) IMAGE_TESTS(double) //////////////////////////////////////// CPP /////////////////////////////// // TEST(Meanshift, Color_CPP) { if (noDoubleTests<float>()) return; vector<dim4> inDims; vector<string> inFiles; vector<dim_type> outSizes; vector<string> outFiles; readImageTests(string(TEST_DIR"/meanshift/color.test"), inDims, inFiles, outSizes, outFiles); size_t testCount = inDims.size(); for (size_t testId=0; testId<testCount; ++testId) { inFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); outFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); af::array img = af::loadImage(inFiles[testId].c_str(), true); af::array gold = af::loadImage(outFiles[testId].c_str(), true); dim_type nElems = gold.elements(); af::array output= af::meanshift(img, 2.25f, 25.56f, 5, true); float * outData = new float[nElems]; output.host((void*)outData); float * goldData= new float[nElems]; gold.host((void*)goldData); ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.07f)); // cleanup delete[] outData; delete[] goldData; } } <commit_msg>Fixed meanshift() unit tests for double data type<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <gtest/gtest.h> #include <arrayfire.h> #include <af/dim4.hpp> #include <af/traits.hpp> #include <string> #include <vector> #include <testHelpers.hpp> #include <cmath> using std::string; using std::vector; using af::dim4; template<typename T> class Meanshift : public ::testing::Test { public: virtual void SetUp() {} }; typedef ::testing::Types<float, double, int, uint, char, uchar> TestTypes; TYPED_TEST_CASE(Meanshift, TestTypes); TYPED_TEST(Meanshift, InvalidArgs) { if (noDoubleTests<TypeParam>()) return; vector<TypeParam> in(100,1); af_array inArray = 0; af_array outArray = 0; af::dim4 dims = af::dim4(100,1,1,1); ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<TypeParam>::af_type)); ASSERT_EQ(AF_ERR_SIZE, af_meanshift(&outArray, inArray, 0.12f, 0.34f, 5, true)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); } template<typename T, bool isColor> void meanshiftTest(string pTestFile) { if (noDoubleTests<T>()) return; vector<dim4> inDims; vector<string> inFiles; vector<dim_type> outSizes; vector<string> outFiles; readImageTests(pTestFile, inDims, inFiles, outSizes, outFiles); size_t testCount = inDims.size(); for (size_t testId=0; testId<testCount; ++testId) { af_array inArray = 0; af_array inArray_f32 = 0; af_array outArray = 0; af_array goldArray = 0; dim_type nElems = 0; inFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); outFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); ASSERT_EQ(AF_SUCCESS, af_load_image(&inArray_f32, inFiles[testId].c_str(), isColor)); ASSERT_EQ(AF_SUCCESS, conv_image<T>(&inArray, inArray_f32)); ASSERT_EQ(AF_SUCCESS, af_load_image(&goldArray, outFiles[testId].c_str(), isColor)); ASSERT_EQ(AF_SUCCESS, af_get_elements(&nElems, goldArray)); ASSERT_EQ(AF_SUCCESS, af_meanshift(&outArray, inArray, 2.25f, 25.56f, 5, isColor)); T * outData = new T[nElems]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray)); T * goldData= new T[nElems]; ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)goldData, goldArray)); ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.07f)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray_f32)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(outArray)); ASSERT_EQ(AF_SUCCESS, af_destroy_array(goldArray)); } } // create a list of types to be tested // FIXME: since af_load_image returns only f32 type arrays // only float, double data types test are enabled & passing // Note: compareArraysRMSD is handling upcasting while working // with two different type of types // #define IMAGE_TESTS(T) \ TEST(Meanshift, Grayscale_##T) \ { \ meanshiftTest<T, false>(string(TEST_DIR"/meanshift/gray.test")); \ } \ TEST(Meanshift, Color_##T) \ { \ meanshiftTest<T, true>(string(TEST_DIR"/meanshift/color.test")); \ } IMAGE_TESTS(float ) IMAGE_TESTS(double) //////////////////////////////////////// CPP /////////////////////////////// // TEST(Meanshift, Color_CPP) { if (noDoubleTests<float>()) return; vector<dim4> inDims; vector<string> inFiles; vector<dim_type> outSizes; vector<string> outFiles; readImageTests(string(TEST_DIR"/meanshift/color.test"), inDims, inFiles, outSizes, outFiles); size_t testCount = inDims.size(); for (size_t testId=0; testId<testCount; ++testId) { inFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); outFiles[testId].insert(0,string(TEST_DIR"/meanshift/")); af::array img = af::loadImage(inFiles[testId].c_str(), true); af::array gold = af::loadImage(outFiles[testId].c_str(), true); dim_type nElems = gold.elements(); af::array output= af::meanshift(img, 2.25f, 25.56f, 5, true); float * outData = new float[nElems]; output.host((void*)outData); float * goldData= new float[nElems]; gold.host((void*)goldData); ASSERT_EQ(true, compareArraysRMSD(nElems, goldData, outData, 0.07f)); // cleanup delete[] outData; delete[] goldData; } } <|endoftext|>
<commit_before>#include "catch.hpp" #include "test/base_test_fixture.h" #include <cstdio> #include <cstdlib> namespace { struct odbc_fixture : public base_test_fixture { odbc_fixture() : base_test_fixture(/* connecting string from NANODBC_TEST_CONNSTR environment variable)*/) { if (connection_string_.empty()) connection_string_ = get_env("NANODBC_TEST_CONNSTR_ODBC"); } virtual ~odbc_fixture() NANODBC_NOEXCEPT { } }; } TEST_CASE_METHOD(odbc_fixture, "driver_test", "[odbc][driver]") { driver_test(); } TEST_CASE_METHOD(odbc_fixture, "blob_test", "[odbc][blob]") { blob_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_columns_test", "[odbc][catalog][columns]") { catalog_columns_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_primary_keys_test", "[odbc][catalog][primary_keys]") { catalog_primary_keys_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_tables_test", "[odbc][catalog][tables]") { catalog_tables_test(); } TEST_CASE_METHOD(odbc_fixture, "dbms_info_test", "[odbc][dmbs][metadata][info]") { dbms_info_test(); } TEST_CASE_METHOD(odbc_fixture, "decimal_conversion_test", "[odbc][decimal][conversion]") { decimal_conversion_test(); } TEST_CASE_METHOD(odbc_fixture, "exception_test", "[odbc][exception]") { exception_test(); } TEST_CASE_METHOD(odbc_fixture, "execute_multiple_transaction_test", "[odbc][execute][transaction]") { execute_multiple_transaction_test(); } TEST_CASE_METHOD(odbc_fixture, "execute_multiple_test", "[odbc][execute]") { execute_multiple_test(); } TEST_CASE_METHOD(odbc_fixture, "integral_test", "[odbc][integral]") { integral_test<odbc_fixture>(); } TEST_CASE_METHOD(odbc_fixture, "move_test", "[odbc][move]") { move_test(); } TEST_CASE_METHOD(odbc_fixture, "null_test", "[odbc][null]") { null_test(); } TEST_CASE_METHOD(odbc_fixture, "nullptr_nulls_test", "[odbc][null]") { nullptr_nulls_test(); } TEST_CASE_METHOD(odbc_fixture, "result_iterator_test", "[odbc][iterator]") { result_iterator_test(); } TEST_CASE_METHOD(odbc_fixture, "simple_test", "[odbc]") { simple_test(); } TEST_CASE_METHOD(odbc_fixture, "string_test", "[odbc][string]") { string_test(); } TEST_CASE_METHOD(odbc_fixture, "transaction_test", "[odbc][transaction]") { transaction_test(); } TEST_CASE_METHOD(odbc_fixture, "while_not_end_iteration_test", "[odbc][looping]") { while_not_end_iteration_test(); } TEST_CASE_METHOD(odbc_fixture, "while_next_iteration_test", "[odbc][looping]") { while_next_iteration_test(); } <commit_msg>Add list_catalogs and list_schemas to generic ODBC test<commit_after>#include "catch.hpp" #include "test/base_test_fixture.h" #include <cstdio> #include <cstdlib> namespace { struct odbc_fixture : public base_test_fixture { odbc_fixture() : base_test_fixture(/* connecting string from NANODBC_TEST_CONNSTR environment variable)*/) { if (connection_string_.empty()) connection_string_ = get_env("NANODBC_TEST_CONNSTR_ODBC"); } virtual ~odbc_fixture() NANODBC_NOEXCEPT { } }; } TEST_CASE_METHOD(odbc_fixture, "driver_test", "[odbc][driver]") { driver_test(); } TEST_CASE_METHOD(odbc_fixture, "blob_test", "[odbc][blob]") { blob_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_list_catalogs_test", "[odbc][catalog][catalogs]") { catalog_list_catalogs_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_list_schemas_test", "[odbc][catalog][schemas]") { catalog_list_schemas_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_columns_test", "[odbc][catalog][columns]") { catalog_columns_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_primary_keys_test", "[odbc][catalog][primary_keys]") { catalog_primary_keys_test(); } TEST_CASE_METHOD(odbc_fixture, "catalog_tables_test", "[odbc][catalog][tables]") { catalog_tables_test(); } TEST_CASE_METHOD(odbc_fixture, "dbms_info_test", "[odbc][dmbs][metadata][info]") { dbms_info_test(); } TEST_CASE_METHOD(odbc_fixture, "decimal_conversion_test", "[odbc][decimal][conversion]") { decimal_conversion_test(); } TEST_CASE_METHOD(odbc_fixture, "exception_test", "[odbc][exception]") { exception_test(); } TEST_CASE_METHOD(odbc_fixture, "execute_multiple_transaction_test", "[odbc][execute][transaction]") { execute_multiple_transaction_test(); } TEST_CASE_METHOD(odbc_fixture, "execute_multiple_test", "[odbc][execute]") { execute_multiple_test(); } TEST_CASE_METHOD(odbc_fixture, "integral_test", "[odbc][integral]") { integral_test<odbc_fixture>(); } TEST_CASE_METHOD(odbc_fixture, "move_test", "[odbc][move]") { move_test(); } TEST_CASE_METHOD(odbc_fixture, "null_test", "[odbc][null]") { null_test(); } TEST_CASE_METHOD(odbc_fixture, "nullptr_nulls_test", "[odbc][null]") { nullptr_nulls_test(); } TEST_CASE_METHOD(odbc_fixture, "result_iterator_test", "[odbc][iterator]") { result_iterator_test(); } TEST_CASE_METHOD(odbc_fixture, "simple_test", "[odbc]") { simple_test(); } TEST_CASE_METHOD(odbc_fixture, "string_test", "[odbc][string]") { string_test(); } TEST_CASE_METHOD(odbc_fixture, "transaction_test", "[odbc][transaction]") { transaction_test(); } TEST_CASE_METHOD(odbc_fixture, "while_not_end_iteration_test", "[odbc][looping]") { while_not_end_iteration_test(); } TEST_CASE_METHOD(odbc_fixture, "while_next_iteration_test", "[odbc][looping]") { while_next_iteration_test(); } <|endoftext|>
<commit_before>/* Test wrappers around POSIX functions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "posix-test.h" #include <errno.h> #include <fcntl.h> #include <climits> #ifdef _WIN32 # include <io.h> # undef max # undef ERROR #endif #include "gtest-extra.h" using fmt::BufferedFile; using fmt::ErrorCode; using fmt::File; namespace { int open_count; int close_count; int dup_count; int dup2_count; int fdopen_count; int read_count; int write_count; int pipe_count; int fopen_count; int fclose_count; int fileno_count; std::size_t read_nbyte; std::size_t write_nbyte; bool sysconf_error; enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim; } #define EMULATE_EINTR(func, error_result) \ if (func##_count != 0) { \ if (func##_count++ != 3) { \ errno = EINTR; \ return error_result; \ } \ } #ifndef _WIN32 int test::open(const char *path, int oflag, int mode) { EMULATE_EINTR(open, -1); return ::open(path, oflag, mode); } static off_t max_file_size() { return std::numeric_limits<off_t>::max(); } int test::fstat(int fd, struct stat *buf) { int result = ::fstat(fd, buf); if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size(); return result; } long test::sysconf(int name) { long result = ::sysconf(name); if (!sysconf_error) return result; // Simulate an error. errno = EINVAL; return -1; } #else errno_t test::sopen_s( int* pfh, const char *filename, int oflag, int shflag, int pmode) { EMULATE_EINTR(open, EINTR); return _sopen_s(pfh, filename, oflag, shflag, pmode); } static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); } BOOL test::GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize) { BOOL result = ::GetFileSizeEx(hFile, lpFileSize); if (fstat_sim == ERROR) { SetLastError(ERROR_ACCESS_DENIED); return FALSE; } if (fstat_sim == MAX_SIZE) lpFileSize->QuadPart = max_file_size(); return result; } #endif int test::close(int fildes) { // Close the file first because close shouldn't be retried. int result = ::FMT_POSIX(close(fildes)); EMULATE_EINTR(close, -1); return result; } int test::dup(int fildes) { EMULATE_EINTR(dup, -1); return ::FMT_POSIX(dup(fildes)); } int test::dup2(int fildes, int fildes2) { EMULATE_EINTR(dup2, -1); return ::FMT_POSIX(dup2(fildes, fildes2)); } FILE *test::fdopen(int fildes, const char *mode) { EMULATE_EINTR(fdopen, 0); return ::FMT_POSIX(fdopen(fildes, mode)); } test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) { read_nbyte = nbyte; EMULATE_EINTR(read, -1); return ::FMT_POSIX(read(fildes, buf, nbyte)); } test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) { write_nbyte = nbyte; EMULATE_EINTR(write, -1); return ::FMT_POSIX(write(fildes, buf, nbyte)); } #ifndef _WIN32 int test::pipe(int fildes[2]) { EMULATE_EINTR(pipe, -1); return ::pipe(fildes); } #else int test::pipe(int *pfds, unsigned psize, int textmode) { EMULATE_EINTR(pipe, -1); return _pipe(pfds, psize, textmode); } #endif FILE *test::fopen(const char *filename, const char *mode) { EMULATE_EINTR(fopen, 0); return ::fopen(filename, mode); } int test::fclose(FILE *stream) { EMULATE_EINTR(fclose, EOF); return ::fclose(stream); } int test::fileno(FILE *stream) { EMULATE_EINTR(fileno, -1); return ::FMT_POSIX(fileno(stream)); } #ifndef _WIN32 # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ statement; \ EXPECT_EQ(4, func##_count); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual) #else # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ EXPECT_SYSTEM_ERROR(statement, EINTR, message); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) #endif void write_file(fmt::StringRef filename, fmt::StringRef content) { fmt::BufferedFile f(filename, "w"); f.print("{}", content); } TEST(UtilTest, StaticAssert) { FMT_STATIC_ASSERT(true, "success"); // Static assertion failure is tested in compile-test because it causes // a compile-time error. } TEST(UtilTest, GetPageSize) { #ifdef _WIN32 SYSTEM_INFO si = {}; GetSystemInfo(&si); EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); #else EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); sysconf_error = true; EXPECT_SYSTEM_ERROR( fmt::getpagesize(), EINVAL, "cannot get memory page size"); sysconf_error = false; #endif } TEST(FileTest, OpenRetry) { write_file("test", "there must be something here"); File *f = 0; EXPECT_RETRY(f = new File("test", File::RDONLY), open, "cannot open file test"); #ifndef _WIN32 char c = 0; f->read(&c, 1); #endif delete f; } TEST(FileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); File *f = new File(std::move(read_end)); int saved_close_count = 0; EXPECT_WRITE(stderr, { close_count = 1; delete f; saved_close_count = close_count; close_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_close_count); } TEST(FileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); close_count = 1; EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); EXPECT_EQ(2, close_count); close_count = 0; } TEST(FileTest, Size) { std::string content = "top secret, destroy before reading"; write_file("test", content); File f("test", File::RDONLY); EXPECT_EQ(content.size(), f.size()); f.close(); #ifdef _WIN32 fmt::Writer message; fmt::internal::format_windows_error( message, ERROR_ACCESS_DENIED, "cannot get file size"); fstat_sim = ERROR; EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str()); fstat_sim = NONE; #else EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes"); #endif } TEST(FileTest, MaxSize) { write_file("test", ""); File f("test", File::RDONLY); fstat_sim = MAX_SIZE; EXPECT_GE(f.size(), 0); EXPECT_EQ(max_file_size(), f.size()); fstat_sim = NONE; } TEST(FileTest, ReadRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; write_end.write("test", SIZE); write_end.close(); char buffer[SIZE]; std::streamsize count = 0; EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, "cannot read from file"); EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count); } TEST(FileTest, WriteRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; std::streamsize count = 0; EXPECT_RETRY(count = write_end.write("test", SIZE), write, "cannot write to file"); write_end.close(); #ifndef _WIN32 EXPECT_EQ(static_cast<std::streamsize>(SIZE), count); char buffer[SIZE + 1]; read_end.read(buffer, SIZE); buffer[SIZE] = '\0'; EXPECT_STREQ("test", buffer); #endif } #ifdef _WIN32 TEST(FileTest, ConvertReadCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; read_count = 1; read_nbyte = 0; EXPECT_THROW(read_end.read(&c, size), fmt::SystemError); read_count = 0; EXPECT_EQ(UINT_MAX, read_nbyte); } TEST(FileTest, ConvertWriteCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; write_count = 1; write_nbyte = 0; EXPECT_THROW(write_end.write(&c, size), fmt::SystemError); write_count = 0; EXPECT_EQ(UINT_MAX, write_nbyte); } #endif TEST(FileTest, DupNoRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); dup_count = 1; EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR, fmt::format("cannot duplicate file descriptor {}", stdout_fd)); dup_count = 0; } TEST(FileTest, Dup2Retry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2, fmt::format("cannot duplicate file descriptor {} to {}", f1.descriptor(), f2.descriptor())); } TEST(FileTest, Dup2NoExceptRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); ErrorCode ec; dup2_count = 1; f1.dup2(f2.descriptor(), ec); #ifndef _WIN32 EXPECT_EQ(4, dup2_count); #else EXPECT_EQ(EINTR, ec.get()); #endif dup2_count = 0; } TEST(FileTest, PipeNoRetry) { File read_end, write_end; pipe_count = 1; EXPECT_SYSTEM_ERROR( File::pipe(read_end, write_end), EINTR, "cannot create pipe"); pipe_count = 0; } TEST(FileTest, FdopenNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); fdopen_count = 1; EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, "cannot associate stream with file descriptor"); fdopen_count = 0; } TEST(BufferedFileTest, OpenRetry) { write_file("test", "there must be something here"); BufferedFile *f = 0; EXPECT_RETRY(f = new BufferedFile("test", "r"), fopen, "cannot open file test"); #ifndef _WIN32 char c = 0; if (fread(&c, 1, 1, f->get()) < 1) throw fmt::SystemError(errno, "fread failed"); #endif delete f; } TEST(BufferedFileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile *f = new BufferedFile(read_end.fdopen("r")); int saved_fclose_count = 0; EXPECT_WRITE(stderr, { fclose_count = 1; delete f; saved_fclose_count = fclose_count; fclose_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_fclose_count); } TEST(BufferedFileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fclose_count = 1; EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); EXPECT_EQ(2, fclose_count); fclose_count = 0; } TEST(BufferedFileTest, FilenoNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fileno_count = 1; EXPECT_SYSTEM_ERROR(f.fileno(), EINTR, "cannot get file descriptor"); EXPECT_EQ(2, fileno_count); fileno_count = 0; } <commit_msg>Fix posix-test, take 3.<commit_after>/* Test wrappers around POSIX functions. Copyright (c) 2012-2014, Victor Zverovich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "posix-test.h" #include <errno.h> #include <fcntl.h> #include <climits> #ifdef _WIN32 # include <io.h> # undef max # undef ERROR #endif #include "gtest-extra.h" using fmt::BufferedFile; using fmt::ErrorCode; using fmt::File; namespace { int open_count; int close_count; int dup_count; int dup2_count; int fdopen_count; int read_count; int write_count; int pipe_count; int fopen_count; int fclose_count; int fileno_count; std::size_t read_nbyte; std::size_t write_nbyte; bool sysconf_error; enum FStatSimulation { NONE, MAX_SIZE, ERROR } fstat_sim; } #define EMULATE_EINTR(func, error_result) \ if (func##_count != 0) { \ if (func##_count++ != 3) { \ errno = EINTR; \ return error_result; \ } \ } #ifndef _WIN32 int test::open(const char *path, int oflag, int mode) { EMULATE_EINTR(open, -1); return ::open(path, oflag, mode); } static off_t max_file_size() { return std::numeric_limits<off_t>::max(); } int test::fstat(int fd, struct stat *buf) { int result = ::fstat(fd, buf); if (fstat_sim == MAX_SIZE) buf->st_size = max_file_size(); return result; } long test::sysconf(int name) { long result = ::sysconf(name); if (!sysconf_error) return result; // Simulate an error. errno = EINVAL; return -1; } #else errno_t test::sopen_s( int* pfh, const char *filename, int oflag, int shflag, int pmode) { EMULATE_EINTR(open, EINTR); return _sopen_s(pfh, filename, oflag, shflag, pmode); } static LONGLONG max_file_size() { return std::numeric_limits<LONGLONG>::max(); } BOOL test::GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize) { if (fstat_sim == ERROR) { SetLastError(ERROR_ACCESS_DENIED); return FALSE; } BOOL result = ::GetFileSizeEx(hFile, lpFileSize); if (fstat_sim == MAX_SIZE) lpFileSize->QuadPart = max_file_size(); return result; } #endif int test::close(int fildes) { // Close the file first because close shouldn't be retried. int result = ::FMT_POSIX(close(fildes)); EMULATE_EINTR(close, -1); return result; } int test::dup(int fildes) { EMULATE_EINTR(dup, -1); return ::FMT_POSIX(dup(fildes)); } int test::dup2(int fildes, int fildes2) { EMULATE_EINTR(dup2, -1); return ::FMT_POSIX(dup2(fildes, fildes2)); } FILE *test::fdopen(int fildes, const char *mode) { EMULATE_EINTR(fdopen, 0); return ::FMT_POSIX(fdopen(fildes, mode)); } test::ssize_t test::read(int fildes, void *buf, test::size_t nbyte) { read_nbyte = nbyte; EMULATE_EINTR(read, -1); return ::FMT_POSIX(read(fildes, buf, nbyte)); } test::ssize_t test::write(int fildes, const void *buf, test::size_t nbyte) { write_nbyte = nbyte; EMULATE_EINTR(write, -1); return ::FMT_POSIX(write(fildes, buf, nbyte)); } #ifndef _WIN32 int test::pipe(int fildes[2]) { EMULATE_EINTR(pipe, -1); return ::pipe(fildes); } #else int test::pipe(int *pfds, unsigned psize, int textmode) { EMULATE_EINTR(pipe, -1); return _pipe(pfds, psize, textmode); } #endif FILE *test::fopen(const char *filename, const char *mode) { EMULATE_EINTR(fopen, 0); return ::fopen(filename, mode); } int test::fclose(FILE *stream) { EMULATE_EINTR(fclose, EOF); return ::fclose(stream); } int test::fileno(FILE *stream) { EMULATE_EINTR(fileno, -1); return ::FMT_POSIX(fileno(stream)); } #ifndef _WIN32 # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ statement; \ EXPECT_EQ(4, func##_count); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) EXPECT_EQ(expected, actual) #else # define EXPECT_RETRY(statement, func, message) \ func##_count = 1; \ EXPECT_SYSTEM_ERROR(statement, EINTR, message); \ func##_count = 0; # define EXPECT_EQ_POSIX(expected, actual) #endif void write_file(fmt::StringRef filename, fmt::StringRef content) { fmt::BufferedFile f(filename, "w"); f.print("{}", content); } TEST(UtilTest, StaticAssert) { FMT_STATIC_ASSERT(true, "success"); // Static assertion failure is tested in compile-test because it causes // a compile-time error. } TEST(UtilTest, GetPageSize) { #ifdef _WIN32 SYSTEM_INFO si = {}; GetSystemInfo(&si); EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); #else EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); sysconf_error = true; EXPECT_SYSTEM_ERROR( fmt::getpagesize(), EINVAL, "cannot get memory page size"); sysconf_error = false; #endif } TEST(FileTest, OpenRetry) { write_file("test", "there must be something here"); File *f = 0; EXPECT_RETRY(f = new File("test", File::RDONLY), open, "cannot open file test"); #ifndef _WIN32 char c = 0; f->read(&c, 1); #endif delete f; } TEST(FileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); File *f = new File(std::move(read_end)); int saved_close_count = 0; EXPECT_WRITE(stderr, { close_count = 1; delete f; saved_close_count = close_count; close_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_close_count); } TEST(FileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); close_count = 1; EXPECT_SYSTEM_ERROR(read_end.close(), EINTR, "cannot close file"); EXPECT_EQ(2, close_count); close_count = 0; } TEST(FileTest, Size) { std::string content = "top secret, destroy before reading"; write_file("test", content); File f("test", File::RDONLY); EXPECT_EQ(content.size(), f.size()); #ifdef _WIN32 fmt::Writer message; fmt::internal::format_windows_error( message, ERROR_ACCESS_DENIED, "cannot get file size"); fstat_sim = ERROR; EXPECT_THROW_MSG(f.size(), fmt::WindowsError, message.str()); fstat_sim = NONE; #else f.close(); EXPECT_SYSTEM_ERROR(f.size(), EBADF, "cannot get file attributes"); #endif } TEST(FileTest, MaxSize) { write_file("test", ""); File f("test", File::RDONLY); fstat_sim = MAX_SIZE; EXPECT_GE(f.size(), 0); EXPECT_EQ(max_file_size(), f.size()); fstat_sim = NONE; } TEST(FileTest, ReadRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; write_end.write("test", SIZE); write_end.close(); char buffer[SIZE]; std::streamsize count = 0; EXPECT_RETRY(count = read_end.read(buffer, SIZE), read, "cannot read from file"); EXPECT_EQ_POSIX(static_cast<std::streamsize>(SIZE), count); } TEST(FileTest, WriteRetry) { File read_end, write_end; File::pipe(read_end, write_end); enum { SIZE = 4 }; std::streamsize count = 0; EXPECT_RETRY(count = write_end.write("test", SIZE), write, "cannot write to file"); write_end.close(); #ifndef _WIN32 EXPECT_EQ(static_cast<std::streamsize>(SIZE), count); char buffer[SIZE + 1]; read_end.read(buffer, SIZE); buffer[SIZE] = '\0'; EXPECT_STREQ("test", buffer); #endif } #ifdef _WIN32 TEST(FileTest, ConvertReadCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; read_count = 1; read_nbyte = 0; EXPECT_THROW(read_end.read(&c, size), fmt::SystemError); read_count = 0; EXPECT_EQ(UINT_MAX, read_nbyte); } TEST(FileTest, ConvertWriteCount) { File read_end, write_end; File::pipe(read_end, write_end); char c; std::size_t size = UINT_MAX; if (sizeof(unsigned) != sizeof(std::size_t)) ++size; write_count = 1; write_nbyte = 0; EXPECT_THROW(write_end.write(&c, size), fmt::SystemError); write_count = 0; EXPECT_EQ(UINT_MAX, write_nbyte); } #endif TEST(FileTest, DupNoRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); dup_count = 1; EXPECT_SYSTEM_ERROR(File::dup(stdout_fd), EINTR, fmt::format("cannot duplicate file descriptor {}", stdout_fd)); dup_count = 0; } TEST(FileTest, Dup2Retry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); EXPECT_RETRY(f1.dup2(f2.descriptor()), dup2, fmt::format("cannot duplicate file descriptor {} to {}", f1.descriptor(), f2.descriptor())); } TEST(FileTest, Dup2NoExceptRetry) { int stdout_fd = FMT_POSIX(fileno(stdout)); File f1 = File::dup(stdout_fd), f2 = File::dup(stdout_fd); ErrorCode ec; dup2_count = 1; f1.dup2(f2.descriptor(), ec); #ifndef _WIN32 EXPECT_EQ(4, dup2_count); #else EXPECT_EQ(EINTR, ec.get()); #endif dup2_count = 0; } TEST(FileTest, PipeNoRetry) { File read_end, write_end; pipe_count = 1; EXPECT_SYSTEM_ERROR( File::pipe(read_end, write_end), EINTR, "cannot create pipe"); pipe_count = 0; } TEST(FileTest, FdopenNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); fdopen_count = 1; EXPECT_SYSTEM_ERROR(read_end.fdopen("r"), EINTR, "cannot associate stream with file descriptor"); fdopen_count = 0; } TEST(BufferedFileTest, OpenRetry) { write_file("test", "there must be something here"); BufferedFile *f = 0; EXPECT_RETRY(f = new BufferedFile("test", "r"), fopen, "cannot open file test"); #ifndef _WIN32 char c = 0; if (fread(&c, 1, 1, f->get()) < 1) throw fmt::SystemError(errno, "fread failed"); #endif delete f; } TEST(BufferedFileTest, CloseNoRetryInDtor) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile *f = new BufferedFile(read_end.fdopen("r")); int saved_fclose_count = 0; EXPECT_WRITE(stderr, { fclose_count = 1; delete f; saved_fclose_count = fclose_count; fclose_count = 0; }, format_system_error(EINTR, "cannot close file") + "\n"); EXPECT_EQ(2, saved_fclose_count); } TEST(BufferedFileTest, CloseNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fclose_count = 1; EXPECT_SYSTEM_ERROR(f.close(), EINTR, "cannot close file"); EXPECT_EQ(2, fclose_count); fclose_count = 0; } TEST(BufferedFileTest, FilenoNoRetry) { File read_end, write_end; File::pipe(read_end, write_end); BufferedFile f = read_end.fdopen("r"); fileno_count = 1; EXPECT_SYSTEM_ERROR(f.fileno(), EINTR, "cannot get file descriptor"); EXPECT_EQ(2, fileno_count); fileno_count = 0; } <|endoftext|>
<commit_before>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <commit_msg>fixed test_upnp<commit_after>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); upnp_handler->discover_device(); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "router: " << upnp_handler->router_model() << std::endl; std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <|endoftext|>
<commit_before>/** * \file * \brief wasteTime() implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-11-03 */ #include "wasteTime.hpp" namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void wasteTime(const TickClock::duration duration) { wasteTime(TickClock::now() + duration + decltype(duration){1}); } void wasteTime(const TickClock::time_point timePoint) { while (timePoint > TickClock::now()); } } // namespace test } // namespace distortos <commit_msg>test: improve precision and reliability of wasteTime()<commit_after>/** * \file * \brief wasteTime() implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-11-04 */ #include "wasteTime.hpp" namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ void wasteTime(const TickClock::duration duration) { /// \todo implementat something more precise and reliable for (TickClock::duration d {}; d <= duration; ++d) wasteTime(TickClock::now() + decltype(duration){1}); } void wasteTime(const TickClock::time_point timePoint) { while (timePoint > TickClock::now()); } } // namespace test } // namespace distortos <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Benoit Jacob <[email protected]> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void zeroSizedMatrix() { MatrixType t1; if (MatrixType::SizeAtCompileTime == Dynamic) { if (MatrixType::RowsAtCompileTime == Dynamic) VERIFY(t1.rows() == 0); if (MatrixType::ColsAtCompileTime == Dynamic) VERIFY(t1.cols() == 0); if (MatrixType::RowsAtCompileTime == Dynamic && MatrixType::ColsAtCompileTime == Dynamic) { MatrixType t2(0, 0); VERIFY(t2.rows() == 0); VERIFY(t2.cols() == 0); } } } template<typename VectorType> void zeroSizedVector() { VectorType t1; if (VectorType::SizeAtCompileTime == Dynamic) { VERIFY(t1.size() == 0); VectorType t2(long(0)); // long disambiguates with 0-the-null-pointer (error with gcc 4.4) VERIFY(t2.size() == 0); } } void test_zerosized() { zeroSizedMatrix<Matrix2d>(); zeroSizedMatrix<Matrix3i>(); zeroSizedMatrix<Matrix<float, 2, Dynamic> >(); zeroSizedMatrix<MatrixXf>(); zeroSizedVector<Vector2d>(); zeroSizedVector<Vector3i>(); zeroSizedVector<VectorXf>(); } <commit_msg>fix MSVC8 compilation<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Benoit Jacob <[email protected]> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void zeroSizedMatrix() { MatrixType t1; if (MatrixType::SizeAtCompileTime == Dynamic) { if (MatrixType::RowsAtCompileTime == Dynamic) VERIFY(t1.rows() == 0); if (MatrixType::ColsAtCompileTime == Dynamic) VERIFY(t1.cols() == 0); if (MatrixType::RowsAtCompileTime == Dynamic && MatrixType::ColsAtCompileTime == Dynamic) { MatrixType t2(0, 0); VERIFY(t2.rows() == 0); VERIFY(t2.cols() == 0); } } } template<typename VectorType> void zeroSizedVector() { VectorType t1; if (VectorType::SizeAtCompileTime == Dynamic) { VERIFY(t1.size() == 0); VectorType t2(DenseIndex(0)); // DenseIndex disambiguates with 0-the-null-pointer (error with gcc 4.4 and MSVC8) VERIFY(t2.size() == 0); } } void test_zerosized() { zeroSizedMatrix<Matrix2d>(); zeroSizedMatrix<Matrix3i>(); zeroSizedMatrix<Matrix<float, 2, Dynamic> >(); zeroSizedMatrix<MatrixXf>(); zeroSizedVector<Vector2d>(); zeroSizedVector<Vector3i>(); zeroSizedVector<VectorXf>(); } <|endoftext|>
<commit_before>#include <iostream> #include "format.hpp" static uint32_t get_words(const char* src, char sch = ' ') noexcept { if(src == nullptr) return 0; uint32_t n = 0; char bc = sch; bool bsc = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(bc == sch && ch != sch) { ++n; } if(ch == 0) break; bc = ch; } } return n; } static bool get_word(const char* src, uint32_t argc, char* dst, uint32_t dstlen, char sch = ' ') noexcept { if(src == nullptr || dst == nullptr || dstlen == 0) return false; uint32_t n = 0; char bc = sch; bool bsc = false; bool out = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(bc == sch && ch != sch) { if(n == argc) { out = true; } ++n; } else if(bc != sch && ch == sch) { if(out) { break; } } if(ch == 0) break; bc = ch; } if(out && dstlen > 1) { *dst++ = ch; dstlen--; } } *dst = 0; return out; } static bool cmp_word(const char* src, uint32_t argc, const char* key, char sch = ' ') noexcept { if(src == nullptr || key == nullptr) return false; uint32_t n = 0; char bc = sch; bool bsc = false; bool out = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(bc == sch && ch != sch) { if(n == argc) { out = true; } ++n; } else if(bc != sch && ch == sch) { if(out) { break; } } if(ch == 0) break; bc = ch; } if(out) { if(ch != *key) return false; ++key; } } if(*key == 0) return true; else return false; } // 速度検査 // #define SPEED_TEST int main(int argc, char* argv[]); int main(int argc, char* argv[]) { { const char* src = "aaa bbb ccc"; auto n = get_words(src); utils::format("'%s': %u\n") % src % n; char dst[256]; n = 0; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; n = 1; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; n = 2; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; } { const char* src = "aaa bbb\\ ccc ddd"; auto n = get_words(src); utils::format("'%s': %u\n") % src % n; char dst[256]; n = 0; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; n = 1; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; n = 2; get_word(src, n, dst, sizeof(dst)); utils::format("%d: '%s'\n") % n % dst; } { const char* src = "aaa bbb\\ ccc ddd"; int f0 = cmp_word(src, 1, "bbb cc"); int f1 = cmp_word(src, 1, "bbb ccc"); int f2 = cmp_word(src, 1, "bbb cccc"); utils::format("%d, %d, %d\n") % f0 % f1 % f2; } } <commit_msg>Update: cleanup<commit_after>#include <iostream> #include "format.hpp" static uint32_t get_words(const char* src, char sch = ' ') noexcept { if(src == nullptr) return 0; uint32_t n = 0; char bc = sch; bool bsc = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(ch == 0) break; if(bc == sch && ch != sch) { ++n; } bc = ch; } } return n; } static bool get_word(const char* src, uint32_t argc, char* dst, uint32_t dstlen, char sch = ' ') noexcept { if(src == nullptr || dst == nullptr || dstlen == 0) return false; uint32_t n = 0; char bc = sch; bool bsc = false; bool out = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(bc == sch && ch != sch) { if(n == argc) { out = true; } ++n; } else if(bc != sch && ch == sch) { if(out) { break; } } if(ch == 0) break; bc = ch; } if(out && dstlen > 1) { *dst++ = ch; dstlen--; } } *dst = 0; return out; } static bool cmp_word(const char* src, uint32_t argc, const char* key, char sch = ' ') noexcept { if(src == nullptr || key == nullptr) return false; uint32_t n = 0; char bc = sch; bool bsc = false; bool out = false; while(1) { char ch = *src++; if(ch == '\\') { bsc = true; continue; } else if(bsc) { bsc = false; } else { if(bc == sch && ch != sch) { if(n == argc) { out = true; } ++n; } else if(bc != sch && ch == sch) { if(out) { break; } } if(ch == 0) break; bc = ch; } if(out) { if(ch != *key) return false; ++key; } } if(*key == 0) return true; else return false; } // 速度検査 // #define SPEED_TEST int main(int argc, char* argv[]); int main(int argc, char* argv[]) { { const char* src = ""; auto n = get_words(src); utils::format("words: '%s': %u\n\n") % src % n; char dst[256]; n = 0; get_word(src, n, dst, sizeof(dst)); utils::format("getw: '%s': %u\n\n") % src % n; } { const char* src = "aaa bbb ccc"; auto n = get_words(src); utils::format("words: '%s': %u\n") % src % n; char dst[256]; n = 0; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n") % n % dst; n = 1; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n") % n % dst; n = 2; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n\n") % n % dst; } { const char* src = "aaa bbb\\ ccc ddd"; auto n = get_words(src); utils::format("words: '%s': %u\n") % src % n; char dst[256]; n = 0; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n") % n % dst; n = 1; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n") % n % dst; n = 2; get_word(src, n, dst, sizeof(dst)); utils::format("getw: %d: '%s'\n\n") % n % dst; } { const char* src = "aaa bbb\\ ccc ddd"; int f0 = cmp_word(src, 1, "bbb cc"); int f1 = cmp_word(src, 1, "bbb ccc"); int f2 = cmp_word(src, 1, "bbb cccc"); utils::format("cmp: %d, %d, %d\n") % f0 % f1 % f2; } } <|endoftext|>
<commit_before>// $Id: NaN_Test.cpp,v 1.1 2004/11/06 00:30:12 othman Exp $ // Test that verifies the MaRC::NaN constant is actually // "Not-A-Number". #include <MaRC/NaN.h> #include <cmath> int main () { return (std::isnan (MaRC::NaN) ? 0 : -1); } <commit_msg>Removed old CVS $ entries and email addresses.<commit_after>// Test that verifies the MaRC::NaN constant is actually // "Not-A-Number". #include <MaRC/NaN.h> #include <cmath> int main () { return (std::isnan (MaRC::NaN) ? 0 : -1); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/plugin/plugin_channel.h" #include "base/bind.h" #include "base/command_line.h" #include "base/process/process_handle.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "build/build_config.h" #include "content/child/child_process.h" #include "content/child/npapi/plugin_instance.h" #include "content/child/npapi/webplugin_delegate_impl.h" #include "content/child/plugin_messages.h" #include "content/common/plugin_process_messages.h" #include "content/plugin/plugin_thread.h" #include "content/plugin/webplugin_delegate_stub.h" #include "content/plugin/webplugin_proxy.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebBindings.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif using blink::WebBindings; namespace content { namespace { // How long we wait before releasing the plugin process. const int kPluginReleaseTimeMinutes = 5; } // namespace // If a sync call to the renderer results in a modal dialog, we need to have a // way to know so that we can run a nested message loop to simulate what would // happen in a single process browser and avoid deadlock. class PluginChannel::MessageFilter : public IPC::ChannelProxy::MessageFilter { public: MessageFilter() : channel_(NULL) { } base::WaitableEvent* GetModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (!modal_dialog_event_map_.count(render_view_id)) { NOTREACHED(); return NULL; } return modal_dialog_event_map_[render_view_id].event; } // Decrement the ref count associated with the modal dialog event for the // given tab. void ReleaseModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (!modal_dialog_event_map_.count(render_view_id)) { NOTREACHED(); return; } if (--(modal_dialog_event_map_[render_view_id].refcount)) return; // Delete the event when the stack unwinds as it could be in use now. base::MessageLoop::current()->DeleteSoon( FROM_HERE, modal_dialog_event_map_[render_view_id].event); modal_dialog_event_map_.erase(render_view_id); } bool Send(IPC::Message* message) { // Need this function for the IPC_MESSAGE_HANDLER_DELAY_REPLY macro. return channel_->Send(message); } // IPC::ChannelProxy::MessageFilter: virtual void OnFilterAdded(IPC::Channel* channel) OVERRIDE { channel_ = channel; } virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { IPC_BEGIN_MESSAGE_MAP(PluginChannel::MessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY(PluginMsg_Init, OnInit) IPC_MESSAGE_HANDLER(PluginMsg_SignalModalDialogEvent, OnSignalModalDialogEvent) IPC_MESSAGE_HANDLER(PluginMsg_ResetModalDialogEvent, OnResetModalDialogEvent) IPC_END_MESSAGE_MAP() return message.type() == PluginMsg_SignalModalDialogEvent::ID || message.type() == PluginMsg_ResetModalDialogEvent::ID; } protected: virtual ~MessageFilter() { // Clean up in case of renderer crash. for (ModalDialogEventMap::iterator i = modal_dialog_event_map_.begin(); i != modal_dialog_event_map_.end(); ++i) { delete i->second.event; } } private: void OnInit(const PluginMsg_Init_Params& params, IPC::Message* reply_msg) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(params.host_render_view_routing_id)) { modal_dialog_event_map_[params.host_render_view_routing_id].refcount++; return; } WaitableEventWrapper wrapper; wrapper.event = new base::WaitableEvent(true, false); wrapper.refcount = 1; modal_dialog_event_map_[params.host_render_view_routing_id] = wrapper; } void OnSignalModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(render_view_id)) modal_dialog_event_map_[render_view_id].event->Signal(); } void OnResetModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(render_view_id)) modal_dialog_event_map_[render_view_id].event->Reset(); } struct WaitableEventWrapper { base::WaitableEvent* event; int refcount; // There could be multiple plugin instances per tab. }; typedef std::map<int, WaitableEventWrapper> ModalDialogEventMap; ModalDialogEventMap modal_dialog_event_map_; base::Lock modal_dialog_event_map_lock_; IPC::Channel* channel_; }; PluginChannel* PluginChannel::GetPluginChannel( int renderer_id, base::MessageLoopProxy* ipc_message_loop) { // Map renderer ID to a (single) channel to that process. std::string channel_key = base::StringPrintf( "%d.r%d", base::GetCurrentProcId(), renderer_id); PluginChannel* channel = static_cast<PluginChannel*>(NPChannelBase::GetChannel( channel_key, IPC::Channel::MODE_SERVER, ClassFactory, ipc_message_loop, false, ChildProcess::current()->GetShutDownEvent())); if (channel) channel->renderer_id_ = renderer_id; return channel; } // static void PluginChannel::NotifyRenderersOfPendingShutdown() { Broadcast(new PluginHostMsg_PluginShuttingDown()); } bool PluginChannel::Send(IPC::Message* msg) { in_send_++; if (log_messages_) { VLOG(1) << "sending message @" << msg << " on channel @" << this << " with type " << msg->type(); } bool result = NPChannelBase::Send(msg); in_send_--; return result; } bool PluginChannel::OnMessageReceived(const IPC::Message& msg) { if (log_messages_) { VLOG(1) << "received message @" << &msg << " on channel @" << this << " with type " << msg.type(); } return NPChannelBase::OnMessageReceived(msg); } void PluginChannel::OnChannelError() { NPChannelBase::OnChannelError(); CleanUp(); } int PluginChannel::GenerateRouteID() { static int last_id = 0; return ++last_id; } base::WaitableEvent* PluginChannel::GetModalDialogEvent(int render_view_id) { return filter_->GetModalDialogEvent(render_view_id); } PluginChannel::~PluginChannel() { PluginThread::current()->Send(new PluginProcessHostMsg_ChannelDestroyed( renderer_id_)); process_ref_.ReleaseWithDelay( base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); } void PluginChannel::CleanUp() { // We need to clean up the stubs so that they call NPPDestroy. This will // also lead to them releasing their reference on this object so that it can // be deleted. for (size_t i = 0; i < plugin_stubs_.size(); ++i) RemoveRoute(plugin_stubs_[i]->instance_id()); // Need to addref this object temporarily because otherwise removing the last // stub will cause the destructor of this object to be called, however at // that point plugin_stubs_ will have one element and its destructor will be // called twice. scoped_refptr<PluginChannel> me(this); plugin_stubs_.clear(); } bool PluginChannel::Init(base::MessageLoopProxy* ipc_message_loop, bool create_pipe_now, base::WaitableEvent* shutdown_event) { if (!NPChannelBase::Init(ipc_message_loop, create_pipe_now, shutdown_event)) return false; channel_->AddFilter(filter_.get()); return true; } PluginChannel::PluginChannel() : renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()), npp_(new struct _NPP) { set_send_unblocking_only_during_unblock_dispatch(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); // Register |npp_| as the default owner for any object we receive via IPC, // and register it with WebBindings as a valid owner. SetDefaultNPObjectOwner(npp_.get()); WebBindings::registerObjectOwner(npp_.get()); } bool PluginChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PluginChannel, msg) IPC_MESSAGE_HANDLER(PluginMsg_CreateInstance, OnCreateInstance) IPC_MESSAGE_HANDLER_DELAY_REPLY(PluginMsg_DestroyInstance, OnDestroyInstance) IPC_MESSAGE_HANDLER(PluginMsg_GenerateRouteID, OnGenerateRouteID) IPC_MESSAGE_HANDLER(PluginProcessMsg_ClearSiteData, OnClearSiteData) IPC_MESSAGE_HANDLER(PluginHostMsg_DidAbortLoading, OnDidAbortLoading) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } void PluginChannel::OnCreateInstance(const std::string& mime_type, int* instance_id) { *instance_id = GenerateRouteID(); scoped_refptr<WebPluginDelegateStub> stub(new WebPluginDelegateStub( mime_type, *instance_id, this)); AddRoute(*instance_id, stub.get(), NULL); plugin_stubs_.push_back(stub); } void PluginChannel::OnDestroyInstance(int instance_id, IPC::Message* reply_msg) { for (size_t i = 0; i < plugin_stubs_.size(); ++i) { if (plugin_stubs_[i]->instance_id() == instance_id) { scoped_refptr<MessageFilter> filter(filter_); int render_view_id = plugin_stubs_[i]->webplugin()->host_render_view_routing_id(); plugin_stubs_.erase(plugin_stubs_.begin() + i); Send(reply_msg); RemoveRoute(instance_id); // NOTE: *this* might be deleted as a result of calling RemoveRoute. // Don't release the modal dialog event right away, but do it after the // stack unwinds since the plugin can be destroyed later if it's in use // right now. base::MessageLoop::current()->PostNonNestableTask( FROM_HERE, base::Bind(&MessageFilter::ReleaseModalDialogEvent, filter.get(), render_view_id)); return; } } NOTREACHED() << "Couldn't find WebPluginDelegateStub to destroy"; } void PluginChannel::OnGenerateRouteID(int* route_id) { *route_id = GenerateRouteID(); } void PluginChannel::OnClearSiteData(const std::string& site, uint64 flags, uint64 max_age) { bool success = false; CommandLine* command_line = CommandLine::ForCurrentProcess(); base::FilePath path = command_line->GetSwitchValuePath(switches::kPluginPath); scoped_refptr<PluginLib> plugin_lib(PluginLib::CreatePluginLib(path)); if (plugin_lib.get()) { NPError err = plugin_lib->NP_Initialize(); if (err == NPERR_NO_ERROR) { const char* site_str = site.empty() ? NULL : site.c_str(); err = plugin_lib->NP_ClearSiteData(site_str, flags, max_age); std::string site_name = site.empty() ? "NULL" : base::StringPrintf("\"%s\"", site_str); VLOG(1) << "NPP_ClearSiteData(" << site_name << ", " << flags << ", " << max_age << ") returned " << err; success = (err == NPERR_NO_ERROR); } } Send(new PluginProcessHostMsg_ClearSiteDataResult(success)); } void PluginChannel::OnDidAbortLoading(int render_view_id) { for (size_t i = 0; i < plugin_stubs_.size(); ++i) { if (plugin_stubs_[i]->webplugin()->host_render_view_routing_id() == render_view_id) { plugin_stubs_[i]->delegate()->instance()->CloseStreams(); } } } } // namespace content <commit_msg>PluginChannel: separate plugin_stubs_.erase and ~WebPluginDelegateStub.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/plugin/plugin_channel.h" #include "base/bind.h" #include "base/command_line.h" #include "base/process/process_handle.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "build/build_config.h" #include "content/child/child_process.h" #include "content/child/npapi/plugin_instance.h" #include "content/child/npapi/webplugin_delegate_impl.h" #include "content/child/plugin_messages.h" #include "content/common/plugin_process_messages.h" #include "content/plugin/plugin_thread.h" #include "content/plugin/webplugin_delegate_stub.h" #include "content/plugin/webplugin_proxy.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebBindings.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif using blink::WebBindings; namespace content { namespace { // How long we wait before releasing the plugin process. const int kPluginReleaseTimeMinutes = 5; } // namespace // If a sync call to the renderer results in a modal dialog, we need to have a // way to know so that we can run a nested message loop to simulate what would // happen in a single process browser and avoid deadlock. class PluginChannel::MessageFilter : public IPC::ChannelProxy::MessageFilter { public: MessageFilter() : channel_(NULL) { } base::WaitableEvent* GetModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (!modal_dialog_event_map_.count(render_view_id)) { NOTREACHED(); return NULL; } return modal_dialog_event_map_[render_view_id].event; } // Decrement the ref count associated with the modal dialog event for the // given tab. void ReleaseModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (!modal_dialog_event_map_.count(render_view_id)) { NOTREACHED(); return; } if (--(modal_dialog_event_map_[render_view_id].refcount)) return; // Delete the event when the stack unwinds as it could be in use now. base::MessageLoop::current()->DeleteSoon( FROM_HERE, modal_dialog_event_map_[render_view_id].event); modal_dialog_event_map_.erase(render_view_id); } bool Send(IPC::Message* message) { // Need this function for the IPC_MESSAGE_HANDLER_DELAY_REPLY macro. return channel_->Send(message); } // IPC::ChannelProxy::MessageFilter: virtual void OnFilterAdded(IPC::Channel* channel) OVERRIDE { channel_ = channel; } virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { IPC_BEGIN_MESSAGE_MAP(PluginChannel::MessageFilter, message) IPC_MESSAGE_HANDLER_DELAY_REPLY(PluginMsg_Init, OnInit) IPC_MESSAGE_HANDLER(PluginMsg_SignalModalDialogEvent, OnSignalModalDialogEvent) IPC_MESSAGE_HANDLER(PluginMsg_ResetModalDialogEvent, OnResetModalDialogEvent) IPC_END_MESSAGE_MAP() return message.type() == PluginMsg_SignalModalDialogEvent::ID || message.type() == PluginMsg_ResetModalDialogEvent::ID; } protected: virtual ~MessageFilter() { // Clean up in case of renderer crash. for (ModalDialogEventMap::iterator i = modal_dialog_event_map_.begin(); i != modal_dialog_event_map_.end(); ++i) { delete i->second.event; } } private: void OnInit(const PluginMsg_Init_Params& params, IPC::Message* reply_msg) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(params.host_render_view_routing_id)) { modal_dialog_event_map_[params.host_render_view_routing_id].refcount++; return; } WaitableEventWrapper wrapper; wrapper.event = new base::WaitableEvent(true, false); wrapper.refcount = 1; modal_dialog_event_map_[params.host_render_view_routing_id] = wrapper; } void OnSignalModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(render_view_id)) modal_dialog_event_map_[render_view_id].event->Signal(); } void OnResetModalDialogEvent(int render_view_id) { base::AutoLock auto_lock(modal_dialog_event_map_lock_); if (modal_dialog_event_map_.count(render_view_id)) modal_dialog_event_map_[render_view_id].event->Reset(); } struct WaitableEventWrapper { base::WaitableEvent* event; int refcount; // There could be multiple plugin instances per tab. }; typedef std::map<int, WaitableEventWrapper> ModalDialogEventMap; ModalDialogEventMap modal_dialog_event_map_; base::Lock modal_dialog_event_map_lock_; IPC::Channel* channel_; }; PluginChannel* PluginChannel::GetPluginChannel( int renderer_id, base::MessageLoopProxy* ipc_message_loop) { // Map renderer ID to a (single) channel to that process. std::string channel_key = base::StringPrintf( "%d.r%d", base::GetCurrentProcId(), renderer_id); PluginChannel* channel = static_cast<PluginChannel*>(NPChannelBase::GetChannel( channel_key, IPC::Channel::MODE_SERVER, ClassFactory, ipc_message_loop, false, ChildProcess::current()->GetShutDownEvent())); if (channel) channel->renderer_id_ = renderer_id; return channel; } // static void PluginChannel::NotifyRenderersOfPendingShutdown() { Broadcast(new PluginHostMsg_PluginShuttingDown()); } bool PluginChannel::Send(IPC::Message* msg) { in_send_++; if (log_messages_) { VLOG(1) << "sending message @" << msg << " on channel @" << this << " with type " << msg->type(); } bool result = NPChannelBase::Send(msg); in_send_--; return result; } bool PluginChannel::OnMessageReceived(const IPC::Message& msg) { if (log_messages_) { VLOG(1) << "received message @" << &msg << " on channel @" << this << " with type " << msg.type(); } return NPChannelBase::OnMessageReceived(msg); } void PluginChannel::OnChannelError() { NPChannelBase::OnChannelError(); CleanUp(); } int PluginChannel::GenerateRouteID() { static int last_id = 0; return ++last_id; } base::WaitableEvent* PluginChannel::GetModalDialogEvent(int render_view_id) { return filter_->GetModalDialogEvent(render_view_id); } PluginChannel::~PluginChannel() { PluginThread::current()->Send(new PluginProcessHostMsg_ChannelDestroyed( renderer_id_)); process_ref_.ReleaseWithDelay( base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); } void PluginChannel::CleanUp() { // We need to clean up the stubs so that they call NPPDestroy. This will // also lead to them releasing their reference on this object so that it can // be deleted. for (size_t i = 0; i < plugin_stubs_.size(); ++i) RemoveRoute(plugin_stubs_[i]->instance_id()); // Need to addref this object temporarily because otherwise removing the last // stub will cause the destructor of this object to be called, however at // that point plugin_stubs_ will have one element and its destructor will be // called twice. scoped_refptr<PluginChannel> me(this); while (!plugin_stubs_.empty()) { // Separate vector::erase and ~WebPluginDelegateStub. // See https://code.google.com/p/chromium/issues/detail?id=314088 scoped_refptr<WebPluginDelegateStub> stub = plugin_stubs_[0]; plugin_stubs_.erase(plugin_stubs_.begin()); } } bool PluginChannel::Init(base::MessageLoopProxy* ipc_message_loop, bool create_pipe_now, base::WaitableEvent* shutdown_event) { if (!NPChannelBase::Init(ipc_message_loop, create_pipe_now, shutdown_event)) return false; channel_->AddFilter(filter_.get()); return true; } PluginChannel::PluginChannel() : renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()), npp_(new struct _NPP) { set_send_unblocking_only_during_unblock_dispatch(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); // Register |npp_| as the default owner for any object we receive via IPC, // and register it with WebBindings as a valid owner. SetDefaultNPObjectOwner(npp_.get()); WebBindings::registerObjectOwner(npp_.get()); } bool PluginChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PluginChannel, msg) IPC_MESSAGE_HANDLER(PluginMsg_CreateInstance, OnCreateInstance) IPC_MESSAGE_HANDLER_DELAY_REPLY(PluginMsg_DestroyInstance, OnDestroyInstance) IPC_MESSAGE_HANDLER(PluginMsg_GenerateRouteID, OnGenerateRouteID) IPC_MESSAGE_HANDLER(PluginProcessMsg_ClearSiteData, OnClearSiteData) IPC_MESSAGE_HANDLER(PluginHostMsg_DidAbortLoading, OnDidAbortLoading) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled); return handled; } void PluginChannel::OnCreateInstance(const std::string& mime_type, int* instance_id) { *instance_id = GenerateRouteID(); scoped_refptr<WebPluginDelegateStub> stub(new WebPluginDelegateStub( mime_type, *instance_id, this)); AddRoute(*instance_id, stub.get(), NULL); plugin_stubs_.push_back(stub); } void PluginChannel::OnDestroyInstance(int instance_id, IPC::Message* reply_msg) { for (size_t i = 0; i < plugin_stubs_.size(); ++i) { if (plugin_stubs_[i]->instance_id() == instance_id) { scoped_refptr<MessageFilter> filter(filter_); int render_view_id = plugin_stubs_[i]->webplugin()->host_render_view_routing_id(); // Separate vector::erase and ~WebPluginDelegateStub. // See https://code.google.com/p/chromium/issues/detail?id=314088 scoped_refptr<WebPluginDelegateStub> stub = plugin_stubs_[i]; plugin_stubs_.erase(plugin_stubs_.begin() + i); stub = NULL; Send(reply_msg); RemoveRoute(instance_id); // NOTE: *this* might be deleted as a result of calling RemoveRoute. // Don't release the modal dialog event right away, but do it after the // stack unwinds since the plugin can be destroyed later if it's in use // right now. base::MessageLoop::current()->PostNonNestableTask( FROM_HERE, base::Bind(&MessageFilter::ReleaseModalDialogEvent, filter.get(), render_view_id)); return; } } NOTREACHED() << "Couldn't find WebPluginDelegateStub to destroy"; } void PluginChannel::OnGenerateRouteID(int* route_id) { *route_id = GenerateRouteID(); } void PluginChannel::OnClearSiteData(const std::string& site, uint64 flags, uint64 max_age) { bool success = false; CommandLine* command_line = CommandLine::ForCurrentProcess(); base::FilePath path = command_line->GetSwitchValuePath(switches::kPluginPath); scoped_refptr<PluginLib> plugin_lib(PluginLib::CreatePluginLib(path)); if (plugin_lib.get()) { NPError err = plugin_lib->NP_Initialize(); if (err == NPERR_NO_ERROR) { const char* site_str = site.empty() ? NULL : site.c_str(); err = plugin_lib->NP_ClearSiteData(site_str, flags, max_age); std::string site_name = site.empty() ? "NULL" : base::StringPrintf("\"%s\"", site_str); VLOG(1) << "NPP_ClearSiteData(" << site_name << ", " << flags << ", " << max_age << ") returned " << err; success = (err == NPERR_NO_ERROR); } } Send(new PluginProcessHostMsg_ClearSiteDataResult(success)); } void PluginChannel::OnDidAbortLoading(int render_view_id) { for (size_t i = 0; i < plugin_stubs_.size(); ++i) { if (plugin_stubs_[i]->webplugin()->host_render_view_routing_id() == render_view_id) { plugin_stubs_[i]->delegate()->instance()->CloseStreams(); } } } } // namespace content <|endoftext|>
<commit_before>// Copyright (c) 2017 Manfeel // [email protected] #include <libsigrok4DSL/libsigrok.h> #include <algorithm> //min/max #include <iostream> #include <Pothos/Framework.hpp> #include <Poco/Logger.h> #include <chrono> #include <random> #include "devicemanager.h" #include "sigsession.h" #include "blockingqueue.hpp" using namespace std; //char DS_RES_PATH[256];//="/usr/local/share/DSView/res/"; /*********************************************************************** * |PothosDoc DSCope(Virtual Oscilloscope) * * The dscope source capture the waveform to an output sample stream. * * The dscope source will post a sample rate stream label named "rxRate" * on the first call to work() after activate() has been called. * Downstream blocks like the plotter widgets can consume this label * and use it to set internal parameters like the axis scaling. * * |category /DreamSourceLab * |category /Sources * |keywords dscope oscilloscope * * * |param sampRate[Sample Rate] The rate of audio samples. * |option [1M] 1e6 * |option [2M] 2e6 * |option [5M] 5e6 * |option [10M] 10e6 * |option [20M] 20e6 * |option [50M] 50e6 * |option [100M] 100e6 * |option [200M] 200e6 * |default 100e6 * |units Sps * |widget ComboBox(editable=true) * * |param vdiv[Voltage Div] The rate of voltage. * |option [10mv] 10 * |option [20mv] 20 * |option [50mv] 50 * |option [100mv] 100 * |option [200mv] 200 * |option [500mv] 500 * |option [1v] 1000 * |option [2v] 2000 * |default 50 * |units mv * |widget ComboBox(editable=true) * * |param logLvl[Debug Log Level] * |option [SR_LOG_NONE] 0 * |option [SR_LOG_ERR] 1 * |option [SR_LOG_WARN] 2 * |option [SR_LOG_INFO] 3 * |option [SR_LOG_DBG] 4 * |option [SR_LOG_SPEW] 5 * |default 2 * * |param dtype[Data Type] The data type produced by the audio source. * |option [Float32] "float32" * |default "float32" * |preview disable * * |factory /dsl/dscope(dtype) * |setter setSamplerate(sampRate) * |setter setVdiv(vdiv) * |setter setLogLevel(logLvl) **********************************************************************/ class DscopeSource : public Pothos::Block { protected: bool _sendLabel = true; struct sr_context *sr_ctx = NULL; DeviceManager *_device_manager = NULL; SigSession *_session = NULL; BlockingQueue<sr_datafeed_dso> *dso_queue = NULL; public: DscopeSource(const Pothos::DType &dtype) { //this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setupDevice)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setSamplerate)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setVdiv)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setLogLevel)); this->setupOutput(0, dtype); //this->setupOutput(1, dtype); // Initialise libsigrok if (sr_init(&sr_ctx) != SR_OK) { throw Pothos::Exception(__func__, "ERROR: libsigrok init failed for the first time!"); } // * |initializer setupDevice(dtype) dso_queue = new BlockingQueue<sr_datafeed_dso>(); _device_manager = new DeviceManager(sr_ctx); _session = new SigSession(*_device_manager, *dso_queue); _session->set_default_device(); if( _session->get_device()->name() != "DSCope") { cout << "ERROR: device DSCope not found!" << endl; destruct(); throw Pothos::Exception(__func__, "ERROR: device DSCope not found!"); } ds_trigger_init(); //_session->register_hotplug_callback(); //_session->start_hotplug_proc(); _session->get_device()->set_ch_enable(1, false); _session->get_device()->set_limit_samples(2048); } ~DscopeSource() { destruct(); } void destruct() { if(dso_queue != NULL) delete dso_queue; if(_device_manager != NULL) delete _device_manager; if(_session != NULL) delete _session; } static Pothos::Block *make(const Pothos::DType &dtype) { return (Pothos::Block*)new DscopeSource(dtype); } void setVdiv(uint64_t vdiv) { _session->get_device()->set_voltage_div(0, vdiv); } void setSamplerate(uint64_t samplerate) { _session->get_device()->set_sample_rate(samplerate); } void setLogLevel(int logLvl) { cout<< __func__ << "(" << logLvl << ") has been called." << endl; sr_log_loglevel_set(logLvl); } void activate(void) { _session->start_capture(false); } void deactivate(void) { _session->stop_capture(); } void work(void) { if (this->workInfo().minOutElements == 0) return; int numFrames = _session->get_device()->get_sample_limit(); numFrames = std::min<int>(numFrames, this->workInfo().minOutElements); auto outPort0 = this->output(0); auto buffer = outPort0->buffer().as<float*>(); const size_t numElems = outPort0->elements(); uint64_t vdiv = _session->get_device()->get_voltage_div(0); sr_datafeed_dso dso = dso_queue->take(); for(uint64_t i=0;i<numElems;i++) { uint8_t b = ((uint8_t *)dso.data)[i]; //buffer[i]=(127.5 - b) * 10 * vdiv / 256.0f; buffer[i]=(127.5 - b) * vdiv / 25.6f; } if (_sendLabel) { _sendLabel = false; const auto rate = _session->get_device()->get_sample_rate(); Pothos::Label label("rxRate", rate, 0); for (auto port : this->outputs()) port->postLabel(label); } //not ready to produce because of backoff //if (_readyTime >= std::chrono::high_resolution_clock::now()) return this->yield(); //produce buffer (all modes) outPort0->produce(numElems); } }; static Pothos::BlockRegistry registerDscope("/dsl/dscope", &DscopeSource::make); <commit_msg>modify deconstruct order to avoid exception.<commit_after>// Copyright (c) 2017 Manfeel // [email protected] #include <libsigrok4DSL/libsigrok.h> #include <algorithm> //min/max #include <iostream> #include <Pothos/Framework.hpp> #include <Poco/Logger.h> #include <chrono> #include <random> #include "devicemanager.h" #include "sigsession.h" #include "blockingqueue.hpp" using namespace std; //char DS_RES_PATH[256];//="/usr/local/share/DSView/res/"; /*********************************************************************** * |PothosDoc DSCope(Virtual Oscilloscope) * * The dscope source capture the waveform to an output sample stream. * * The dscope source will post a sample rate stream label named "rxRate" * on the first call to work() after activate() has been called. * Downstream blocks like the plotter widgets can consume this label * and use it to set internal parameters like the axis scaling. * * |category /DreamSourceLab * |category /Sources * |keywords dscope oscilloscope * * * |param sampRate[Sample Rate] The rate of audio samples. * |option [1M] 1e6 * |option [2M] 2e6 * |option [5M] 5e6 * |option [10M] 10e6 * |option [20M] 20e6 * |option [50M] 50e6 * |option [100M] 100e6 * |option [200M] 200e6 * |default 100e6 * |units Sps * |widget ComboBox(editable=true) * * |param vdiv[Voltage Div] The rate of voltage. * |option [10mv] 10 * |option [20mv] 20 * |option [50mv] 50 * |option [100mv] 100 * |option [200mv] 200 * |option [500mv] 500 * |option [1v] 1000 * |option [2v] 2000 * |default 50 * |units mv * |widget ComboBox(editable=true) * * |param logLvl[Debug Log Level] * |option [SR_LOG_NONE] 0 * |option [SR_LOG_ERR] 1 * |option [SR_LOG_WARN] 2 * |option [SR_LOG_INFO] 3 * |option [SR_LOG_DBG] 4 * |option [SR_LOG_SPEW] 5 * |default 2 * * |param dtype[Data Type] The data type produced by the audio source. * |option [Float32] "float32" * |default "float32" * |preview disable * * |factory /dsl/dscope(dtype) * |setter setSamplerate(sampRate) * |setter setVdiv(vdiv) * |setter setLogLevel(logLvl) **********************************************************************/ class DscopeSource : public Pothos::Block { protected: bool _sendLabel = true; struct sr_context *sr_ctx = NULL; DeviceManager *_device_manager = NULL; SigSession *_session = NULL; BlockingQueue<sr_datafeed_dso> *dso_queue = NULL; public: DscopeSource(const Pothos::DType &dtype) { //this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setupDevice)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setSamplerate)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setVdiv)); this->registerCall(this, POTHOS_FCN_TUPLE(DscopeSource, setLogLevel)); this->setupOutput(0, dtype); //this->setupOutput(1, dtype); // Initialise libsigrok if (sr_init(&sr_ctx) != SR_OK) { throw Pothos::Exception(__func__, "ERROR: libsigrok init failed for the first time!"); } // * |initializer setupDevice(dtype) dso_queue = new BlockingQueue<sr_datafeed_dso>(); _device_manager = new DeviceManager(sr_ctx); _session = new SigSession(*_device_manager, *dso_queue); _session->set_default_device(); if( _session->get_device()->name() != "DSCope") { cout << "ERROR: device DSCope not found!" << endl; destruct(); throw Pothos::Exception(__func__, "ERROR: device DSCope not found!"); } ds_trigger_init(); //_session->register_hotplug_callback(); //_session->start_hotplug_proc(); _session->get_device()->set_ch_enable(1, false); _session->get_device()->set_limit_samples(2048); } ~DscopeSource() { destruct(); } void destruct() { if(_session != NULL) delete _session; if(_device_manager != NULL) delete _device_manager; if(dso_queue != NULL) delete dso_queue; } static Pothos::Block *make(const Pothos::DType &dtype) { return (Pothos::Block*)new DscopeSource(dtype); } void setVdiv(uint64_t vdiv) { _session->get_device()->set_voltage_div(0, vdiv); } void setSamplerate(uint64_t samplerate) { _session->get_device()->set_sample_rate(samplerate); } void setLogLevel(int logLvl) { cout<< __func__ << "(" << logLvl << ") has been called." << endl; sr_log_loglevel_set(logLvl); } void activate(void) { _session->start_capture(false); } void deactivate(void) { _session->stop_capture(); } void work(void) { if (this->workInfo().minOutElements == 0) return; int numFrames = _session->get_device()->get_sample_limit(); numFrames = std::min<int>(numFrames, this->workInfo().minOutElements); auto outPort0 = this->output(0); auto buffer = outPort0->buffer().as<float*>(); const size_t numElems = outPort0->elements(); uint64_t vdiv = _session->get_device()->get_voltage_div(0); sr_datafeed_dso dso = dso_queue->take(); for(uint64_t i=0;i<numElems;i++) { uint8_t b = ((uint8_t *)dso.data)[i]; //buffer[i]=(127.5 - b) * 10 * vdiv / 256.0f; buffer[i]=(127.5 - b) * vdiv / 25.6f; } if (_sendLabel) { _sendLabel = false; const auto rate = _session->get_device()->get_sample_rate(); Pothos::Label label("rxRate", rate, 0); for (auto port : this->outputs()) port->postLabel(label); } //not ready to produce because of backoff //if (_readyTime >= std::chrono::high_resolution_clock::now()) return this->yield(); //produce buffer (all modes) outPort0->produce(numElems); } }; static Pothos::BlockRegistry registerDscope("/dsl/dscope", &DscopeSource::make); <|endoftext|>
<commit_before>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "LanguageModelSRI.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" #include "StaticData.h" using namespace std; namespace Moses { LanguageModelSRI::LanguageModelSRI(bool registerScore, ScoreIndexManager &scoreIndexManager) :LanguageModelPointerState(registerScore, scoreIndexManager) , m_srilmVocab(0) , m_srilmModel(0) { } LanguageModelSRI::~LanguageModelSRI() { delete m_srilmModel; delete m_srilmVocab; } bool LanguageModelSRI::Load(const std::string &filePath , FactorType factorType , size_t nGramOrder) { m_srilmVocab = new ::Vocab(); m_srilmModel = new Ngram(*m_srilmVocab, nGramOrder); m_factorType = factorType; m_nGramOrder = nGramOrder; m_filePath = filePath; m_srilmModel->skipOOVs() = false; File file( filePath.c_str(), "r" ); m_srilmModel->read(file); // LM can be ok, just outputs warnings CreateFactors(); m_unknownId = m_srilmVocab->unkIndex(); return true; } void LanguageModelSRI::CreateFactors() { // add factors which have srilm id FactorCollection &factorCollection = FactorCollection::Instance(); std::map<size_t, VocabIndex> lmIdMap; size_t maxFactorId = 0; // to create lookup vector later on VocabString str; VocabIter iter(*m_srilmVocab); while ( (str = iter.next()) != NULL) { VocabIndex lmId = GetLmID(str); size_t factorId = factorCollection.AddFactor(Output, m_factorType, str)->GetId(); lmIdMap[factorId] = lmId; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_); factorId = m_sentenceStart->GetId(); lmIdMap[factorId] = GetLmID(BOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_); factorId = m_sentenceEnd->GetId(); lmIdMap[factorId] = GetLmID(EOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_lmIdLookup.resize(maxFactorId+1); fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId); map<size_t, VocabIndex>::iterator iterMap; for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap) { m_lmIdLookup[iterMap->first] = iterMap->second; } } VocabIndex LanguageModelSRI::GetLmID( const std::string &str ) const { return m_srilmVocab->getIndex( str.c_str(), m_unknownId ); } VocabIndex LanguageModelSRI::GetLmID( const Factor *factor ) const { size_t factorId = factor->GetId(); return ( factorId >= m_lmIdLookup.size()) ? m_unknownId : m_lmIdLookup[factorId]; } float LanguageModelSRI::GetValue(VocabIndex wordId, VocabIndex *context) const { float p = m_srilmModel->wordProb( wordId, context ); return FloorScore(TransformLMScore(p)); // log10->log } float LanguageModelSRI::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int *len) const { FactorType factorType = GetFactorType(); size_t count = contextFactor.size(); if (count <= 0) { finalState = NULL; return 0; } // set up context VocabIndex context[MAX_NGRAM_SIZE]; for (size_t i = 0 ; i < count - 1 ; i++) { context[i] = GetLmID((*contextFactor[count-2-i])[factorType]); } context[count-1] = Vocab_None; assert((*contextFactor[count-1])[factorType] != NULL); // call sri lm fn VocabIndex lmId= GetLmID((*contextFactor[count-1])[factorType]); float ret = GetValue(lmId, context); if (finalState) { for (int i = count - 2 ; i >= 0 ; i--) context[i+1] = context[i]; context[0] = lmId; unsigned int dummy; if (!len) { len = &dummy; } *finalState = m_srilmModel->contextID(context,*len); (*len)++; } return ret; } } <commit_msg>Bugfixes in srilm adaptor.<commit_after>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "LanguageModelSRI.h" #include "TypeDef.h" #include "Util.h" #include "FactorCollection.h" #include "Phrase.h" #include "StaticData.h" using namespace std; namespace Moses { LanguageModelSRI::LanguageModelSRI(bool registerScore, ScoreIndexManager &scoreIndexManager) :LanguageModelPointerState(registerScore, scoreIndexManager) , m_srilmVocab(0) , m_srilmModel(0) { } LanguageModelSRI::~LanguageModelSRI() { delete m_srilmModel; delete m_srilmVocab; } bool LanguageModelSRI::Load(const std::string &filePath , FactorType factorType , size_t nGramOrder) { m_srilmVocab = new ::Vocab(); m_srilmModel = new Ngram(*m_srilmVocab, nGramOrder); m_factorType = factorType; m_nGramOrder = nGramOrder; m_filePath = filePath; m_srilmModel->skipOOVs() = false; File file( filePath.c_str(), "r" ); m_srilmModel->read(file); // LM can be ok, just outputs warnings CreateFactors(); m_unknownId = m_srilmVocab->unkIndex(); return true; } void LanguageModelSRI::CreateFactors() { // add factors which have srilm id FactorCollection &factorCollection = FactorCollection::Instance(); std::map<size_t, VocabIndex> lmIdMap; size_t maxFactorId = 0; // to create lookup vector later on VocabString str; VocabIter iter(*m_srilmVocab); while ( (str = iter.next()) != NULL) { VocabIndex lmId = GetLmID(str); size_t factorId = factorCollection.AddFactor(Output, m_factorType, str)->GetId(); lmIdMap[factorId] = lmId; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_); factorId = m_sentenceStart->GetId(); lmIdMap[factorId] = GetLmID(BOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_); factorId = m_sentenceEnd->GetId(); lmIdMap[factorId] = GetLmID(EOS_); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_lmIdLookup.resize(maxFactorId+1); fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId); map<size_t, VocabIndex>::iterator iterMap; for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap) { m_lmIdLookup[iterMap->first] = iterMap->second; } } VocabIndex LanguageModelSRI::GetLmID( const std::string &str ) const { return m_srilmVocab->getIndex( str.c_str(), m_unknownId ); } VocabIndex LanguageModelSRI::GetLmID( const Factor *factor ) const { size_t factorId = factor->GetId(); return ( factorId >= m_lmIdLookup.size()) ? m_unknownId : m_lmIdLookup[factorId]; } float LanguageModelSRI::GetValue(VocabIndex wordId, VocabIndex *context) const { float p = m_srilmModel->wordProb( wordId, context ); return FloorScore(TransformLMScore(p)); // log10->log } float LanguageModelSRI::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int *len) const { FactorType factorType = GetFactorType(); size_t count = contextFactor.size(); if (count <= 0) { if(finalState) *finalState = NULL; return 0; } // set up context VocabIndex ngram[count + 1]; for (size_t i = 0 ; i < count - 1 ; i++) { ngram[i+1] = GetLmID((*contextFactor[count-2-i])[factorType]); } ngram[count] = Vocab_None; assert((*contextFactor[count-1])[factorType] != NULL); // call sri lm fn VocabIndex lmId = GetLmID((*contextFactor[count-1])[factorType]); float ret = GetValue(lmId, ngram+1); if (finalState) { ngram[0] = lmId; unsigned int dummy; if (!len) { len = &dummy; } *finalState = m_srilmModel->contextID(ngram, *len); (*len)++; } return ret; } } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $ // $Revision: 1.22 $ // $Name: $ // $Author: shoops $ // $Date: 2008/04/23 17:42:50 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include "CQExpressionWidget.h" #include "CQMessageBox.h" #include "CCopasiSelectionDialog.h" #include "qtUtilities.h" #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew) : QSyntaxHighlighter(ew) {} int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */) { int pos = 0; int oldpos = -1; int delta; while (true) { pos = text.find("<", pos); if (pos == -1) delta = 0; else delta = pos - oldpos - 1; setFormat(oldpos + 1, delta, QColor(0, 0, 0)); if (pos == -1) break; oldpos = pos; pos = text.find(">", pos); while (pos > 0 && text[pos - 1] == '\\') pos = text.find(">", pos + 1); if (pos == -1) delta = 0; else delta = pos - oldpos + 1; setFormat(oldpos, delta, QColor(200, 0, 0)); if (pos == -1) break; oldpos = pos; } return 0; } //*********************************************************************** CQValidatorExpression::CQValidatorExpression(QTextEdit * parent, const char * name): CQValidator< QTextEdit >(parent, name), mExpression() {} /** * This function ensures that any characters on Expression Widget are validated * to go to further processes. */ QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const { // std::cout << "CQVE::validate(__) " << (const char *) input.utf8() << std::endl; if (const_cast< CExpression * >(&mExpression)->setInfix((const char *) input.utf8()) && const_cast< CExpression * >(&mExpression)->compile()) { QString Input = mpLineEdit->text(); // std::cout << mpLineEdit->text() << std::endl; return CQValidator< QTextEdit >::validate(Input, pos); } setColor(Invalid); return Intermediate; } /** * Function to get CExpression object */ CExpression *CQValidatorExpression::getExpression() { // return const_cast< CExpression * >(&mExpression); return &mExpression; } //*********************************************************************** CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name) : QTextEdit(parent, name), mOldPar(0), mOldPos(0), mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION), mpCurrentObject(NULL), mNewName("") { setTextFormat(PlainText); setTabChangesFocus(true); new CQExpressionHighlighter(this); int h, s, v; mSavedColor = paletteBackgroundColor(); mSavedColor.getHsv(&h, &s, &v); if (s < 20) s = 20; mChangedColor.setHsv(240, s, v); mpValidator = new CQValidatorExpression(this); mpValidator->revalidate(); connect(this, SIGNAL(cursorPositionChanged(int, int)), this, SLOT(slotCursorPositionChanged(int, int))); connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); connect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged())); } void CQExpressionWidget::keyPressEvent (QKeyEvent * e) { //filter "<" and ">" if (e->text() == "<") return; if (e->text() == ">") return; QTextEdit::keyPressEvent(e); } void CQExpressionWidget::slotSelectionChanged() { int par1, par2, pos1, pos2; getSelection(&par1, &pos1, &par2, &pos2); if (par1 == -1) //no selection, do nothing { getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); return; } //debug output // std::cout << "sc: " << par1 << ", " // << pos1 << ", " // << par2 << ", " // << pos2 << ", " << std::endl; //make sure a selection contains an object completely or not at all //TODO bool iio1 = isInObject(par1, pos1); bool iio2 = isInObject(par2, pos2); // std::cout << iio1 << " " << iio2 << std::endl; //if both borders are outside do nothing. //if at least one is inside clear selection if (iio1 || iio2) removeSelection(); //TODO: right now the any invalid selection is just cleared. //in some cases it would be nicer for the user if it would be //extended instead getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); } /** * This slot checks any characters that are newly typed on Expression Widget. */ void CQExpressionWidget::slotTextChanged() { // std::cout << "CQEW::slotTextChanged()" << std::endl; int pos = 0; QString Expression = FROM_UTF8(getExpression()); emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable); } void CQExpressionWidget::slotCursorPositionChanged(int para, int pos) { //debug output //std::cout << "cpc: " << para << ", " << pos << " . " << isInObject() << std::endl; //check if we are inside an object if (isInObject(para, pos)) { int newpos; //first decide in which direction we want to leave the object if (compareCursorPositions(mOldPar, mOldPos, para, pos)) { //move right newpos = text(para).find(">", pos); if (newpos != -1) setCursorPosition(para, newpos + 1); } else { //move left newpos = text(para).findRev("<", pos); if (newpos != -1) setCursorPosition(para, newpos); } } getCursorPosition(&mOldPar, &mOldPos); } bool CQExpressionWidget::isInObject() { int para, pos; getCursorPosition(&para, &pos); return isInObject(para, pos); /* //the following code assumes the presence of the syntax highlighter if (color() == QColor(0,0,0)) return false; if (pos==0) return false; QString t = text(para); if (t[pos-1] == '>') return false; return true;*/ } bool CQExpressionWidget::isInObject(int par, int pos) { if (pos == 0) return false; bool result = false; QString tmp = text(par); //std::cout << "iio? " << par << " " << pos << std::endl; //first look to the left int lo, lc; lo = tmp.findRev('<', pos - 1); lc = tmp.findRev('>', pos - 1); while (lc > 0 && tmp[lc - 1] == '\\') lc = tmp.findRev('>', lc - 1); //std::cout << "left:" << lo << " " << lc << std::endl; if ((lo == -1) && (lc == -1)) result = false; else if (lc == -1) result = true; else if (lo == -1) { //std::cout << "inconsistent expression!" << std::endl; result = false; } else if (lo < lc) result = false; else // lo > lc result = true; //TODO: we could implement a consistency check by trying to find the same //information from looking to the right. return result; } bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos) { if (par > parold) return true; if (par < parold) return false; //we are in the same paragraph if (pos > posold) return true; return false; } void CQExpressionWidget::doKeyboardAction(QTextEdit::KeyboardAction action) { int para, pos; getCursorPosition(&para, &pos); //handle backspace and delete. All other actions are ignored switch (action) { case QTextEdit::ActionBackspace: if (pos == 0) return; if (text(para)[pos - 1] == '>') { //std::cout << "Backspace into object." << std::endl; QString tmp = text(para); int left = tmp.findRev('<', pos); setSelection(para, left, para, pos); removeSelectedText(); //std::cout << pos << " " << left << std::endl; } else QTextEdit::doKeyboardAction(action); break; case QTextEdit::ActionDelete: if ((unsigned int) pos == text().length()) return; if (text(para)[pos] == '<') { //std::cout << "Delete into object." << std::endl; QString tmp = text(para); int right = tmp.find('>', pos); setSelection(para, pos, para, right + 1); removeSelectedText(); //std::cout << pos << " " << right << std::endl; } else QTextEdit::doKeyboardAction(action); break; default: QTextEdit::doKeyboardAction(action); break; } } void CQExpressionWidget::setExpression(const std::string & expression) { // Reset the parse list. mParseList.clear(); std::string Expression = expression; std::string out_str = ""; unsigned C_INT32 i = 0; while (i < Expression.length()) { if (Expression[i] == '<') { i++; std::string objectName = ""; while (Expression[i] != '>' && i < Expression.length()) { if (Expression[i] == '\\') objectName += Expression[i++]; objectName += Expression[i]; i++; } CCopasiObjectName temp_CN(objectName); CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN)); if (temp_object != NULL) { std::string DisplayName = temp_object->getObjectDisplayName(); mParseList[DisplayName] = temp_object; // We need to escape > std::string::size_type pos = DisplayName.find_first_of("\\>"); while (pos != std::string::npos) { DisplayName.insert(pos, "\\"); pos += 2; pos = DisplayName.find_first_of("\\>", pos); } out_str += "<" + DisplayName + ">"; } continue; } else if (Expression[i] == '>') { //do nothing } else { out_str += Expression[i]; } i++; } setText(FROM_UTF8(out_str)); mpValidator->saved(); return; } std::string CQExpressionWidget::getExpression() const { std::string DisplayName = ""; std::string InfixCN = ""; std::string InfixDispayName = (const char *)text().utf8(); std::map< std::string, const CCopasiObject *>::const_iterator it; for (unsigned int i = 0; i < InfixDispayName.length(); i++) { InfixCN += InfixDispayName[i]; DisplayName = ""; if (InfixDispayName[i] == '<') { i++; while (i < InfixDispayName.length() && InfixDispayName[i] != '>') { if (InfixDispayName[i] == '\\') // '\' is an escape character. i++; DisplayName += InfixDispayName[i++]; } it = mParseList.find(DisplayName); if (it != mParseList.end()) InfixCN += it->second->getCN() + ">"; else InfixCN = InfixCN.substr(0, InfixCN.length() - 1); } } return InfixCN; } /* CExpression *CQExpressionWidget::getExpression() { // return const_cast< CExpression * >(&mExpression); return &(mpValidator->mExpression); }*/ void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType) { mExpressionType = expressionType; } void CQExpressionWidget::slotSelectObject() { const CCopasiObject * pObject = CCopasiSelectionDialog::getObjectSingle(this, mExpressionType); if (pObject) { // Check whether the object is valid if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject)) { CQMessageBox::critical(this, "Invalid Selection", "The use of the selected object is not allowed in this type of expression."); return; } std::string Insert = pObject->getObjectDisplayName(); mParseList[Insert] = pObject; // We need to escape > std::string::size_type pos = Insert.find_first_of("\\>"); while (pos != std::string::npos) { Insert.insert(pos, "\\"); pos += 2; pos = Insert.find_first_of("\\>", pos); } insert(FROM_UTF8("<" + Insert + ">")); } } <commit_msg>Change color of selected object on expression widget<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $ // $Revision: 1.23 $ // $Name: $ // $Author: pwilly $ // $Date: 2008/05/16 11:23:02 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include "CQExpressionWidget.h" #include "CQMessageBox.h" #include "CCopasiSelectionDialog.h" #include "qtUtilities.h" #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew) : QSyntaxHighlighter(ew) {} int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */) { int pos = 0; int oldpos = -1; int delta; while (true) { pos = text.find("<", pos); if (pos == -1) delta = 0; else delta = pos - oldpos - 1; setFormat(oldpos + 1, delta, QColor(0, 0, 0)); if (pos == -1) break; oldpos = pos; pos = text.find(">", pos); while (pos > 0 && text[pos - 1] == '\\') pos = text.find(">", pos + 1); if (pos == -1) delta = 0; else delta = pos - oldpos + 1; setFormat(oldpos, delta, QColor(100, 0, 200)); if (pos == -1) break; oldpos = pos; } return 0; } //*********************************************************************** CQValidatorExpression::CQValidatorExpression(QTextEdit * parent, const char * name): CQValidator< QTextEdit >(parent, name), mExpression() {} /** * This function ensures that any characters on Expression Widget are validated * to go to further processes. */ QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const { // std::cout << "CQVE::validate(__) " << (const char *) input.utf8() << std::endl; if (const_cast< CExpression * >(&mExpression)->setInfix((const char *) input.utf8()) && const_cast< CExpression * >(&mExpression)->compile()) { QString Input = mpLineEdit->text(); // std::cout << mpLineEdit->text() << std::endl; return CQValidator< QTextEdit >::validate(Input, pos); } setColor(Invalid); return Intermediate; } /** * Function to get CExpression object */ CExpression *CQValidatorExpression::getExpression() { // return const_cast< CExpression * >(&mExpression); return &mExpression; } //*********************************************************************** CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name) : QTextEdit(parent, name), mOldPar(0), mOldPos(0), mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION), mpCurrentObject(NULL), mNewName("") { setTextFormat(PlainText); setTabChangesFocus(true); new CQExpressionHighlighter(this); int h, s, v; mSavedColor = paletteBackgroundColor(); mSavedColor.getHsv(&h, &s, &v); if (s < 20) s = 20; mChangedColor.setHsv(240, s, v); mpValidator = new CQValidatorExpression(this); mpValidator->revalidate(); connect(this, SIGNAL(cursorPositionChanged(int, int)), this, SLOT(slotCursorPositionChanged(int, int))); connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); connect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged())); } void CQExpressionWidget::keyPressEvent (QKeyEvent * e) { //filter "<" and ">" if (e->text() == "<") return; if (e->text() == ">") return; QTextEdit::keyPressEvent(e); } void CQExpressionWidget::slotSelectionChanged() { int par1, par2, pos1, pos2; getSelection(&par1, &pos1, &par2, &pos2); if (par1 == -1) //no selection, do nothing { getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); return; } //debug output // std::cout << "sc: " << par1 << ", " // << pos1 << ", " // << par2 << ", " // << pos2 << ", " << std::endl; //make sure a selection contains an object completely or not at all //TODO bool iio1 = isInObject(par1, pos1); bool iio2 = isInObject(par2, pos2); // std::cout << iio1 << " " << iio2 << std::endl; //if both borders are outside do nothing. //if at least one is inside clear selection if (iio1 || iio2) removeSelection(); //TODO: right now the any invalid selection is just cleared. //in some cases it would be nicer for the user if it would be //extended instead getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); } /** * This slot checks any characters that are newly typed on Expression Widget. */ void CQExpressionWidget::slotTextChanged() { // std::cout << "CQEW::slotTextChanged()" << std::endl; int pos = 0; QString Expression = FROM_UTF8(getExpression()); emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable); } void CQExpressionWidget::slotCursorPositionChanged(int para, int pos) { //debug output //std::cout << "cpc: " << para << ", " << pos << " . " << isInObject() << std::endl; //check if we are inside an object if (isInObject(para, pos)) { int newpos; //first decide in which direction we want to leave the object if (compareCursorPositions(mOldPar, mOldPos, para, pos)) { //move right newpos = text(para).find(">", pos); if (newpos != -1) setCursorPosition(para, newpos + 1); } else { //move left newpos = text(para).findRev("<", pos); if (newpos != -1) setCursorPosition(para, newpos); } } getCursorPosition(&mOldPar, &mOldPos); } bool CQExpressionWidget::isInObject() { int para, pos; getCursorPosition(&para, &pos); return isInObject(para, pos); /* //the following code assumes the presence of the syntax highlighter if (color() == QColor(0,0,0)) return false; if (pos==0) return false; QString t = text(para); if (t[pos-1] == '>') return false; return true;*/ } bool CQExpressionWidget::isInObject(int par, int pos) { if (pos == 0) return false; bool result = false; QString tmp = text(par); //std::cout << "iio? " << par << " " << pos << std::endl; //first look to the left int lo, lc; lo = tmp.findRev('<', pos - 1); lc = tmp.findRev('>', pos - 1); while (lc > 0 && tmp[lc - 1] == '\\') lc = tmp.findRev('>', lc - 1); //std::cout << "left:" << lo << " " << lc << std::endl; if ((lo == -1) && (lc == -1)) result = false; else if (lc == -1) result = true; else if (lo == -1) { //std::cout << "inconsistent expression!" << std::endl; result = false; } else if (lo < lc) result = false; else // lo > lc result = true; //TODO: we could implement a consistency check by trying to find the same //information from looking to the right. return result; } bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos) { if (par > parold) return true; if (par < parold) return false; //we are in the same paragraph if (pos > posold) return true; return false; } void CQExpressionWidget::doKeyboardAction(QTextEdit::KeyboardAction action) { int para, pos; getCursorPosition(&para, &pos); //handle backspace and delete. All other actions are ignored switch (action) { case QTextEdit::ActionBackspace: if (pos == 0) return; if (text(para)[pos - 1] == '>') { //std::cout << "Backspace into object." << std::endl; QString tmp = text(para); int left = tmp.findRev('<', pos); setSelection(para, left, para, pos); removeSelectedText(); //std::cout << pos << " " << left << std::endl; } else QTextEdit::doKeyboardAction(action); break; case QTextEdit::ActionDelete: if ((unsigned int) pos == text().length()) return; if (text(para)[pos] == '<') { //std::cout << "Delete into object." << std::endl; QString tmp = text(para); int right = tmp.find('>', pos); setSelection(para, pos, para, right + 1); removeSelectedText(); //std::cout << pos << " " << right << std::endl; } else QTextEdit::doKeyboardAction(action); break; default: QTextEdit::doKeyboardAction(action); break; } } void CQExpressionWidget::setExpression(const std::string & expression) { // Reset the parse list. mParseList.clear(); std::string Expression = expression; std::string out_str = ""; unsigned C_INT32 i = 0; while (i < Expression.length()) { if (Expression[i] == '<') { i++; std::string objectName = ""; while (Expression[i] != '>' && i < Expression.length()) { if (Expression[i] == '\\') objectName += Expression[i++]; objectName += Expression[i]; i++; } CCopasiObjectName temp_CN(objectName); CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN)); if (temp_object != NULL) { std::string DisplayName = temp_object->getObjectDisplayName(); mParseList[DisplayName] = temp_object; // We need to escape > std::string::size_type pos = DisplayName.find_first_of("\\>"); while (pos != std::string::npos) { DisplayName.insert(pos, "\\"); pos += 2; pos = DisplayName.find_first_of("\\>", pos); } out_str += "<" + DisplayName + ">"; } continue; } else if (Expression[i] == '>') { //do nothing } else { out_str += Expression[i]; } i++; } setText(FROM_UTF8(out_str)); mpValidator->saved(); return; } std::string CQExpressionWidget::getExpression() const { std::string DisplayName = ""; std::string InfixCN = ""; std::string InfixDispayName = (const char *)text().utf8(); std::map< std::string, const CCopasiObject *>::const_iterator it; for (unsigned int i = 0; i < InfixDispayName.length(); i++) { InfixCN += InfixDispayName[i]; DisplayName = ""; if (InfixDispayName[i] == '<') { i++; while (i < InfixDispayName.length() && InfixDispayName[i] != '>') { if (InfixDispayName[i] == '\\') // '\' is an escape character. i++; DisplayName += InfixDispayName[i++]; } it = mParseList.find(DisplayName); if (it != mParseList.end()) InfixCN += it->second->getCN() + ">"; else InfixCN = InfixCN.substr(0, InfixCN.length() - 1); } } return InfixCN; } /* CExpression *CQExpressionWidget::getExpression() { // return const_cast< CExpression * >(&mExpression); return &(mpValidator->mExpression); }*/ void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType) { mExpressionType = expressionType; } void CQExpressionWidget::slotSelectObject() { const CCopasiObject * pObject = CCopasiSelectionDialog::getObjectSingle(this, mExpressionType); if (pObject) { // Check whether the object is valid if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject)) { CQMessageBox::critical(this, "Invalid Selection", "The use of the selected object is not allowed in this type of expression."); return; } std::string Insert = pObject->getObjectDisplayName(); mParseList[Insert] = pObject; // We need to escape > std::string::size_type pos = Insert.find_first_of("\\>"); while (pos != std::string::npos) { Insert.insert(pos, "\\"); pos += 2; pos = Insert.find_first_of("\\>", pos); } insert(FROM_UTF8("<" + Insert + ">")); } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2010 Juergen Riegel <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include <App/Plane.h> #include <Base/Placement.h> #include "Feature.h" #include "Body.h" #include "BodyPy.h" #include "FeatureSketchBased.h" #include "FeatureTransformed.h" #include "DatumPoint.h" #include "DatumLine.h" #include "DatumPlane.h" #include <App/Application.h> #include <App/Document.h> #include <Base/Console.h> #include <Mod/Part/App/DatumFeature.h> using namespace PartDesign; namespace PartDesign { PROPERTY_SOURCE(PartDesign::Body, Part::BodyBase) Body::Body() { ADD_PROPERTY(IsActive,(0)); } /* // Note: The following code will catch Python Document::removeObject() modifications. If the object removed is // a member of the Body::Model, then it will be automatically removed from the Model property which triggers the // following two methods // But since we require the Python user to call both Document::addObject() and Body::addFeature(), we should // also require calling both Document::removeObject and Body::removeFeature() in order to be consistent void Body::onBeforeChange(const App::Property *prop) { // Remember the feature before the current Tip. If the Tip is already at the first feature, remember the next feature if (prop == &Model) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) { rememberTip = NULL; } else { std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); if (it == features.begin()) { it++; if (it == features.end()) rememberTip = NULL; else rememberTip = *it; } else { it--; rememberTip = *it; } } } return Part::Feature::onBeforeChange(prop); } void Body::onChanged(const App::Property *prop) { if (prop == &Model) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) { Tip.setValue(NULL); } else { std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); if (it == features.end()) { // Tip feature was deleted Tip.setValue(rememberTip); } } } return Part::Feature::onChanged(prop); } */ short Body::mustExecute() const { if (Tip.isTouched() ) return 1; return 0; } const Part::TopoShape Body::getTipShape() { // TODO right selection for Body App::DocumentObject* link = Tip.getValue(); if (!link) return Part::TopoShape(); if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) //return new App::DocumentObjectExecReturn("Linked object is not a PartDesign object"); return Part::TopoShape(); // get the shape of the tip return static_cast<Part::Feature*>(link)->Shape.getShape(); } App::DocumentObject* Body::getPrevFeature(App::DocumentObject *start) const { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (st == NULL) return st; // Tip is NULL std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object it--; return *it; } App::DocumentObject* Body::getPrevSolidFeature(App::DocumentObject *start, const bool inclusive) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (st == NULL) return st; // Tip is NULL if (inclusive && isSolidFeature(st)) return st; std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object // Skip sketches and datum features do { if (it == features.begin()) return NULL; it--; } while (!isSolidFeature(*it)); return *it; } App::DocumentObject* Body::getNextSolidFeature(App::DocumentObject *start, const bool inclusive) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (inclusive && isSolidFeature(st)) return st; std::vector<App::DocumentObject*>::iterator it; if (st == NULL) it = features.begin(); // Tip is NULL else it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object // Skip sketches and datum features do { it++; if (it == features.end()) return NULL; } while (!isSolidFeature(*it)); return *it; } const bool Body::isMemberOfMultiTransform(const App::DocumentObject* f) { if (f == NULL) return false; // This can be recognized because the Originals property is empty (it is contained // in the MultiTransform instead) return (f->getTypeId().isDerivedFrom(PartDesign::Transformed::getClassTypeId()) && static_cast<const PartDesign::Transformed*>(f)->Originals.getValues().empty()); } const bool Body::isSolidFeature(const App::DocumentObject* f) { if (f == NULL) return false; if (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId())) { // Transformed Features inside a MultiTransform are not solid features return !isMemberOfMultiTransform(f); } } const bool Body::isAllowed(const App::DocumentObject* f) { if (f == NULL) return false; // TODO: Should we introduce a PartDesign::FeaturePython class? This should then also return true for isSolidFeature() return (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) || f->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) || f->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()) || f->getTypeId().isDerivedFrom(Part::FeaturePython::getClassTypeId())); } void Body::addFeature(App::DocumentObject *feature) { // Set the BaseFeature property if (feature->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId())) { App::DocumentObject* prevSolidFeature = getPrevSolidFeature(NULL, true); if (prevSolidFeature != NULL) // Set BaseFeature property to previous feature (this might be the Tip feature) static_cast<PartDesign::Feature*>(feature)->BaseFeature.setValue(prevSolidFeature); } if (Body::isSolidFeature(feature)) { // Reroute the next solid feature's BaseFeature property to this feature App::DocumentObject* nextSolidFeature = getNextSolidFeature(NULL, false); if (nextSolidFeature != NULL) static_cast<PartDesign::Feature*>(nextSolidFeature)->BaseFeature.setValue(feature); } // Insert the new feature after the current Tip feature App::DocumentObject* tipFeature = Tip.getValue(); std::vector<App::DocumentObject*> model = Model.getValues(); if (tipFeature == NULL) { if (model.empty()) // First feature in the body model.push_back(feature); else // Insert feature as before all other features in the body model.insert(model.begin(), feature); } else { // Insert after Tip std::vector<App::DocumentObject*>::iterator it = std::find(model.begin(), model.end(), tipFeature); if (it == model.end()) throw Base::Exception("Body: Tip is not contained in model"); it++; if (it == model.end()) model.push_back(feature); else model.insert(it, feature); } Model.setValues(model); // Move the Tip Tip.setValue(feature); } void Body::removeFeature(App::DocumentObject* feature) { // This method must be called BEFORE the feature is removed from the Document! if (isSolidFeature(feature)) { // This is a solid feature // If the next feature is solid, reroute its BaseFeature property to the previous solid feature App::DocumentObject* nextSolidFeature = getNextSolidFeature(feature, false); if (nextSolidFeature != NULL) { App::DocumentObject* prevSolidFeature = getPrevSolidFeature(feature, false); PartDesign::Feature* nextFeature = static_cast<PartDesign::Feature*>(nextSolidFeature); if ((prevSolidFeature == NULL) && (nextFeature->BaseFeature.getValue() != NULL)) // sanity check throw Base::Exception((std::string("Body: Base feature of ") + nextFeature->getNameInDocument() + " was removed!").c_str()); nextFeature->BaseFeature.setValue(prevSolidFeature); } } std::vector<App::DocumentObject*> model = Model.getValues(); std::vector<App::DocumentObject*>::iterator it = std::find(model.begin(), model.end(), feature); // Adjust Tip feature if it is pointing to the deleted object App::DocumentObject* tipFeature = Tip.getValue(); if (tipFeature == feature) { // Set the Tip to the previous feature if possible, otherwise to the next feature std::vector<App::DocumentObject*>::const_iterator prev = it, next = it; if (it != model.begin()) { prev--; next++; if (prev != model.end()) { Tip.setValue(*prev); } else { if (next != model.end()) Tip.setValue(*next); else Tip.setValue(NULL); } } else { next++; if (next != model.end()) Tip.setValue(*next); else Tip.setValue(NULL); } } // Erase feature from Model model.erase(it); Model.setValues(model); } App::DocumentObjectExecReturn *Body::execute(void) { /* Base::Console().Error("Body '%s':\n", getNameInDocument()); App::DocumentObject* tip = Tip.getValue(); Base::Console().Error(" Tip: %s\n", (tip == NULL) ? "None" : tip->getNameInDocument()); std::vector<App::DocumentObject*> model = Model.getValues(); Base::Console().Error(" Model:\n"); for (std::vector<App::DocumentObject*>::const_iterator m = model.begin(); m != model.end(); m++) { if (*m == NULL) continue; Base::Console().Error(" %s", (*m)->getNameInDocument()); if (Body::isSolidFeature(*m)) { App::DocumentObject* baseFeature = static_cast<PartDesign::Feature*>(*m)->BaseFeature.getValue(); Base::Console().Error(", Base: %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); } else { Base::Console().Error("\n"); } } */ const Part::TopoShape& TipShape = getTipShape(); if (TipShape._Shape.IsNull()) //return new App::DocumentObjectExecReturn("empty shape"); return App::DocumentObject::StdReturn; Shape.setValue(TipShape); return App::DocumentObject::StdReturn; } Base::BoundBox3d Body::getBoundBox() { Base::BoundBox3d result; Part::Feature* tipSolid = static_cast<Part::Feature*>(getPrevSolidFeature()); if (tipSolid != NULL) { if (tipSolid->Shape.getValue().IsNull()) // This can happen when a new feature is added without having its Shape property set yet tipSolid = static_cast<Part::Feature*>(getPrevSolidFeature(NULL, false)); if (tipSolid != NULL) { if (tipSolid->Shape.getValue().IsNull()) tipSolid = NULL; else result = tipSolid->Shape.getShape().getBoundBox(); } } if (tipSolid == NULL) result = App::Plane::getBoundBox(); std::vector<App::DocumentObject*> model = Model.getValues(); // TODO: In DatumLine and DatumPlane, recalculate the Base point to be as near as possible to the origin (0,0,0) for (std::vector<App::DocumentObject*>::const_iterator m = model.begin(); m != model.end(); m++) { if ((*m)->getTypeId().isDerivedFrom(PartDesign::Point::getClassTypeId())) { PartDesign::Point* point = static_cast<PartDesign::Point*>(*m); result.Add(point->getPoint()); } else if ((*m)->getTypeId().isDerivedFrom(PartDesign::Line::getClassTypeId())) { PartDesign::Line* line = static_cast<PartDesign::Line*>(*m); result.Add(line->getBasePoint()); } else if ((*m)->getTypeId().isDerivedFrom(PartDesign::Plane::getClassTypeId())) { PartDesign::Plane* plane = static_cast<PartDesign::Plane*>(*m); result.Add(plane->getBasePoint()); } else if ((*m)->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { // Note: We only take into account the base planes here result.Add(Base::Vector3d(0,0,0)); } } return result; } PyObject *Body::getPyObject(void) { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 PythonObject = Py::Object(new BodyPy(this),true); } return Py::new_reference_to(PythonObject); } } <commit_msg>Workaround for a wired linker problem on Windows. Actually still not solved...<commit_after>/*************************************************************************** * Copyright (c) 2010 Juergen Riegel <[email protected]> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include <App/Plane.h> #include <Base/Placement.h> #include "Feature.h" #include "Body.h" #include "BodyPy.h" #include "FeatureSketchBased.h" #include "FeatureTransformed.h" #include "DatumPoint.h" #include "DatumLine.h" #include "DatumPlane.h" #include <App/Application.h> #include <App/Document.h> #include <Base/Console.h> #include <Mod/Part/App/DatumFeature.h> #include <Mod/Part/App/PartFeature.h> using namespace PartDesign; namespace PartDesign { PROPERTY_SOURCE(PartDesign::Body, Part::BodyBase) Body::Body() { ADD_PROPERTY(IsActive,(0)); } /* // Note: The following code will catch Python Document::removeObject() modifications. If the object removed is // a member of the Body::Model, then it will be automatically removed from the Model property which triggers the // following two methods // But since we require the Python user to call both Document::addObject() and Body::addFeature(), we should // also require calling both Document::removeObject and Body::removeFeature() in order to be consistent void Body::onBeforeChange(const App::Property *prop) { // Remember the feature before the current Tip. If the Tip is already at the first feature, remember the next feature if (prop == &Model) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) { rememberTip = NULL; } else { std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); if (it == features.begin()) { it++; if (it == features.end()) rememberTip = NULL; else rememberTip = *it; } else { it--; rememberTip = *it; } } } return Part::Feature::onBeforeChange(prop); } void Body::onChanged(const App::Property *prop) { if (prop == &Model) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) { Tip.setValue(NULL); } else { std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); if (it == features.end()) { // Tip feature was deleted Tip.setValue(rememberTip); } } } return Part::Feature::onChanged(prop); } */ short Body::mustExecute() const { if (Tip.isTouched() ) return 1; return 0; } const Part::TopoShape Body::getTipShape() { // TODO right selection for Body App::DocumentObject* link = Tip.getValue(); if (!link) return Part::TopoShape(); if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) //return new App::DocumentObjectExecReturn("Linked object is not a PartDesign object"); return Part::TopoShape(); // get the shape of the tip return static_cast<Part::Feature*>(link)->Shape.getShape(); } App::DocumentObject* Body::getPrevFeature(App::DocumentObject *start) const { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (st == NULL) return st; // Tip is NULL std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object it--; return *it; } App::DocumentObject* Body::getPrevSolidFeature(App::DocumentObject *start, const bool inclusive) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (st == NULL) return st; // Tip is NULL if (inclusive && isSolidFeature(st)) return st; std::vector<App::DocumentObject*>::iterator it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object // Skip sketches and datum features do { if (it == features.begin()) return NULL; it--; } while (!isSolidFeature(*it)); return *it; } App::DocumentObject* Body::getNextSolidFeature(App::DocumentObject *start, const bool inclusive) { std::vector<App::DocumentObject*> features = Model.getValues(); if (features.empty()) return NULL; App::DocumentObject* st = (start == NULL ? Tip.getValue() : start); if (inclusive && isSolidFeature(st)) return st; std::vector<App::DocumentObject*>::iterator it; if (st == NULL) it = features.begin(); // Tip is NULL else it = std::find(features.begin(), features.end(), st); if (it == features.end()) return NULL; // Invalid start object // Skip sketches and datum features do { it++; if (it == features.end()) return NULL; } while (!isSolidFeature(*it)); return *it; } const bool Body::isMemberOfMultiTransform(const App::DocumentObject* f) { if (f == NULL) return false; // This can be recognized because the Originals property is empty (it is contained // in the MultiTransform instead) return (f->getTypeId().isDerivedFrom(PartDesign::Transformed::getClassTypeId()) && static_cast<const PartDesign::Transformed*>(f)->Originals.getValues().empty()); } const bool Body::isSolidFeature(const App::DocumentObject* f) { if (f == NULL) return false; if (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId())) { // Transformed Features inside a MultiTransform are not solid features return !isMemberOfMultiTransform(f); } } const bool Body::isAllowed(const App::DocumentObject* f) { if (f == NULL) return false; // TODO: Should we introduce a PartDesign::FeaturePython class? This should then also return true for isSolidFeature() return (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) || f->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) || f->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()) || //f->getTypeId().isDerivedFrom(Part::FeaturePython::getClassTypeId()) // trouble with this line on Windows!? Linker fails to find getClassTypeId() of the Part::FeaturePython... f->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()) ); } void Body::addFeature(App::DocumentObject *feature) { // Set the BaseFeature property if (feature->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId())) { App::DocumentObject* prevSolidFeature = getPrevSolidFeature(NULL, true); if (prevSolidFeature != NULL) // Set BaseFeature property to previous feature (this might be the Tip feature) static_cast<PartDesign::Feature*>(feature)->BaseFeature.setValue(prevSolidFeature); } if (Body::isSolidFeature(feature)) { // Reroute the next solid feature's BaseFeature property to this feature App::DocumentObject* nextSolidFeature = getNextSolidFeature(NULL, false); if (nextSolidFeature != NULL) static_cast<PartDesign::Feature*>(nextSolidFeature)->BaseFeature.setValue(feature); } // Insert the new feature after the current Tip feature App::DocumentObject* tipFeature = Tip.getValue(); std::vector<App::DocumentObject*> model = Model.getValues(); if (tipFeature == NULL) { if (model.empty()) // First feature in the body model.push_back(feature); else // Insert feature as before all other features in the body model.insert(model.begin(), feature); } else { // Insert after Tip std::vector<App::DocumentObject*>::iterator it = std::find(model.begin(), model.end(), tipFeature); if (it == model.end()) throw Base::Exception("Body: Tip is not contained in model"); it++; if (it == model.end()) model.push_back(feature); else model.insert(it, feature); } Model.setValues(model); // Move the Tip Tip.setValue(feature); } void Body::removeFeature(App::DocumentObject* feature) { // This method must be called BEFORE the feature is removed from the Document! if (isSolidFeature(feature)) { // This is a solid feature // If the next feature is solid, reroute its BaseFeature property to the previous solid feature App::DocumentObject* nextSolidFeature = getNextSolidFeature(feature, false); if (nextSolidFeature != NULL) { App::DocumentObject* prevSolidFeature = getPrevSolidFeature(feature, false); PartDesign::Feature* nextFeature = static_cast<PartDesign::Feature*>(nextSolidFeature); if ((prevSolidFeature == NULL) && (nextFeature->BaseFeature.getValue() != NULL)) // sanity check throw Base::Exception((std::string("Body: Base feature of ") + nextFeature->getNameInDocument() + " was removed!").c_str()); nextFeature->BaseFeature.setValue(prevSolidFeature); } } std::vector<App::DocumentObject*> model = Model.getValues(); std::vector<App::DocumentObject*>::iterator it = std::find(model.begin(), model.end(), feature); // Adjust Tip feature if it is pointing to the deleted object App::DocumentObject* tipFeature = Tip.getValue(); if (tipFeature == feature) { // Set the Tip to the previous feature if possible, otherwise to the next feature std::vector<App::DocumentObject*>::const_iterator prev = it, next = it; if (it != model.begin()) { prev--; next++; if (prev != model.end()) { Tip.setValue(*prev); } else { if (next != model.end()) Tip.setValue(*next); else Tip.setValue(NULL); } } else { next++; if (next != model.end()) Tip.setValue(*next); else Tip.setValue(NULL); } } // Erase feature from Model model.erase(it); Model.setValues(model); } App::DocumentObjectExecReturn *Body::execute(void) { /* Base::Console().Error("Body '%s':\n", getNameInDocument()); App::DocumentObject* tip = Tip.getValue(); Base::Console().Error(" Tip: %s\n", (tip == NULL) ? "None" : tip->getNameInDocument()); std::vector<App::DocumentObject*> model = Model.getValues(); Base::Console().Error(" Model:\n"); for (std::vector<App::DocumentObject*>::const_iterator m = model.begin(); m != model.end(); m++) { if (*m == NULL) continue; Base::Console().Error(" %s", (*m)->getNameInDocument()); if (Body::isSolidFeature(*m)) { App::DocumentObject* baseFeature = static_cast<PartDesign::Feature*>(*m)->BaseFeature.getValue(); Base::Console().Error(", Base: %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); } else { Base::Console().Error("\n"); } } */ const Part::TopoShape& TipShape = getTipShape(); if (TipShape._Shape.IsNull()) //return new App::DocumentObjectExecReturn("empty shape"); return App::DocumentObject::StdReturn; Shape.setValue(TipShape); return App::DocumentObject::StdReturn; } Base::BoundBox3d Body::getBoundBox() { Base::BoundBox3d result; Part::Feature* tipSolid = static_cast<Part::Feature*>(getPrevSolidFeature()); if (tipSolid != NULL) { if (tipSolid->Shape.getValue().IsNull()) // This can happen when a new feature is added without having its Shape property set yet tipSolid = static_cast<Part::Feature*>(getPrevSolidFeature(NULL, false)); if (tipSolid != NULL) { if (tipSolid->Shape.getValue().IsNull()) tipSolid = NULL; else result = tipSolid->Shape.getShape().getBoundBox(); } } if (tipSolid == NULL) result = App::Plane::getBoundBox(); std::vector<App::DocumentObject*> model = Model.getValues(); // TODO: In DatumLine and DatumPlane, recalculate the Base point to be as near as possible to the origin (0,0,0) for (std::vector<App::DocumentObject*>::const_iterator m = model.begin(); m != model.end(); m++) { if ((*m)->getTypeId().isDerivedFrom(PartDesign::Point::getClassTypeId())) { PartDesign::Point* point = static_cast<PartDesign::Point*>(*m); result.Add(point->getPoint()); } else if ((*m)->getTypeId().isDerivedFrom(PartDesign::Line::getClassTypeId())) { PartDesign::Line* line = static_cast<PartDesign::Line*>(*m); result.Add(line->getBasePoint()); } else if ((*m)->getTypeId().isDerivedFrom(PartDesign::Plane::getClassTypeId())) { PartDesign::Plane* plane = static_cast<PartDesign::Plane*>(*m); result.Add(plane->getBasePoint()); } else if ((*m)->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { // Note: We only take into account the base planes here result.Add(Base::Vector3d(0,0,0)); } } return result; } PyObject *Body::getPyObject(void) { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 PythonObject = Py::Object(new BodyPy(this),true); } return Py::new_reference_to(PythonObject); } } <|endoftext|>
<commit_before><commit_msg>PVS: V1016 Value is out of range of enum values. This causes unspecified or undefined behavior.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/unit_test.h" #include <stdio.h> #include "bin/builtin.h" #include "bin/dartutils.h" #include "bin/isolate_data.h" #include "platform/globals.h" #include "vm/assembler.h" #include "vm/ast_printer.h" #include "vm/compiler.h" #include "vm/dart_api_impl.h" #include "vm/disassembler.h" #include "vm/isolate_reload.h" #include "vm/parser.h" #include "vm/symbols.h" #include "vm/thread.h" #include "vm/virtual_memory.h" using dart::bin::Builtin; using dart::bin::DartUtils; namespace dart { TestCaseBase* TestCaseBase::first_ = NULL; TestCaseBase* TestCaseBase::tail_ = NULL; TestCaseBase::TestCaseBase(const char* name) : next_(NULL), name_(name) { if (first_ == NULL) { first_ = this; } else { tail_->next_ = this; } tail_ = this; } void TestCaseBase::RunAll() { TestCaseBase* test = first_; while (test != NULL) { test->RunTest(); test = test->next_; } } Dart_Isolate TestCase::CreateIsolate(const uint8_t* buffer, const char* name) { bin::IsolateData* isolate_data = new bin::IsolateData(name, NULL, NULL); char* err; Dart_Isolate isolate = Dart_CreateIsolate( name, NULL, buffer, NULL, isolate_data, &err); if (isolate == NULL) { OS::Print("Creation of isolate failed '%s'\n", err); free(err); } EXPECT(isolate != NULL); return isolate; } static const char* kPackageScheme = "package:"; static bool IsPackageSchemeURL(const char* url_name) { static const intptr_t kPackageSchemeLen = strlen(kPackageScheme); return (strncmp(url_name, kPackageScheme, kPackageSchemeLen) == 0); } static bool IsImportableTestLib(const char* url_name) { const char* kImportTestLibUri = "test:importable_lib"; static const intptr_t kImportTestLibUriLen = strlen(kImportTestLibUri); return (strncmp(url_name, kImportTestLibUri, kImportTestLibUriLen) == 0); } static Dart_Handle ImportableTestLibSource() { const char* kScript = "importedFunc() => 'a';\n" "importedIntFunc() => 4;\n" "class ImportedMixin {\n" " mixinFunc() => 'mixin';\n" "}\n"; return DartUtils::NewString(kScript); } #ifndef PRODUCT static bool IsIsolateReloadTestLib(const char* url_name) { const char* kIsolateReloadTestLibUri = "test:isolate_reload_helper"; static const intptr_t kIsolateReloadTestLibUriLen = strlen(kIsolateReloadTestLibUri); return (strncmp(url_name, kIsolateReloadTestLibUri, kIsolateReloadTestLibUriLen) == 0); } static Dart_Handle IsolateReloadTestLibSource() { // Special library with one function. return DartUtils::NewString("void reloadTest() native 'Reload_Test';\n"); } static void ReloadTest(Dart_NativeArguments native_args) { DART_CHECK_VALID(TestCase::TriggerReload()); } static Dart_NativeFunction IsolateReloadTestNativeResolver( Dart_Handle name, int num_of_arguments, bool* auto_setup_scope) { return ReloadTest; } #endif // !PRODUCT static Dart_Handle ResolvePackageUri(const char* uri_chars) { const int kNumArgs = 1; Dart_Handle dart_args[kNumArgs]; dart_args[0] = DartUtils::NewString(uri_chars); return Dart_Invoke(DartUtils::BuiltinLib(), DartUtils::NewString("_filePathFromUri"), kNumArgs, dart_args); } static ThreadLocalKey script_reload_key = kUnsetThreadLocalKey; static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, Dart_Handle library, Dart_Handle url) { if (tag == Dart_kCanonicalizeUrl) { Dart_Handle library_url = Dart_LibraryUrl(library); if (Dart_IsError(library_url)) { return library_url; } return Dart_DefaultCanonicalizeUrl(library_url, url); } if (tag == Dart_kScriptTag) { // Reload request. ASSERT(script_reload_key != kUnsetThreadLocalKey); const char* script_source = reinterpret_cast<const char*>( OSThread::GetThreadLocal(script_reload_key)); ASSERT(script_source != NULL); OSThread::SetThreadLocal(script_reload_key, 0); return Dart_LoadScript(url, NewString(script_source), 0, 0); } if (!Dart_IsLibrary(library)) { return Dart_NewApiError("not a library"); } if (!Dart_IsString(url)) { return Dart_NewApiError("url is not a string"); } const char* url_chars = NULL; Dart_Handle result = Dart_StringToCString(url, &url_chars); if (Dart_IsError(result)) { return Dart_NewApiError("accessing url characters failed"); } Dart_Handle library_url = Dart_LibraryUrl(library); const char* library_url_string = NULL; result = Dart_StringToCString(library_url, &library_url_string); if (Dart_IsError(result)) { return result; } bool is_dart_scheme_url = DartUtils::IsDartSchemeURL(url_chars); bool is_io_library = DartUtils::IsDartIOLibURL(library_url_string); if (is_dart_scheme_url) { ASSERT(tag == Dart_kImportTag); // Handle imports of other built-in libraries present in the SDK. if (DartUtils::IsDartIOLibURL(url_chars)) { return Builtin::LoadAndCheckLibrary(Builtin::kIOLibrary); } else if (DartUtils::IsDartBuiltinLibURL(url_chars)) { return Builtin::LoadAndCheckLibrary(Builtin::kBuiltinLibrary); } else { return DartUtils::NewError("Do not know how to load '%s'", url_chars); } } if (IsImportableTestLib(url_chars)) { return Dart_LoadLibrary(url, ImportableTestLibSource(), 0, 0); } NOT_IN_PRODUCT( if (IsIsolateReloadTestLib(url_chars)) { Dart_Handle library = Dart_LoadLibrary(url, IsolateReloadTestLibSource(), 0, 0); DART_CHECK_VALID(library); Dart_SetNativeResolver(library, IsolateReloadTestNativeResolver, 0); return library; }) if (is_io_library) { ASSERT(tag == Dart_kSourceTag); return Dart_LoadSource(library, url, Builtin::PartSource(Builtin::kIOLibrary, url_chars), 0, 0); } if (IsPackageSchemeURL(url_chars)) { Dart_Handle resolved_uri = ResolvePackageUri(url_chars); DART_CHECK_VALID(resolved_uri); url_chars = NULL; Dart_Handle result = Dart_StringToCString(resolved_uri, &url_chars); if (Dart_IsError(result)) { return Dart_NewApiError("accessing url characters failed"); } } // Do sync loading since unit_test doesn't support async. Dart_Handle source = DartUtils::ReadStringFromFile(url_chars); EXPECT_VALID(source); if (tag == Dart_kImportTag) { return Dart_LoadLibrary(url, source, 0, 0); } else { ASSERT(tag == Dart_kSourceTag); return Dart_LoadSource(library, url, source, 0, 0); } } Dart_Handle TestCase::LoadTestScript(const char* script, Dart_NativeEntryResolver resolver, const char* lib_url, bool finalize_classes) { Dart_Handle url = NewString(lib_url); Dart_Handle source = NewString(script); Dart_Handle result = Dart_SetLibraryTagHandler(LibraryTagHandler); EXPECT_VALID(result); Dart_Handle lib = Dart_LoadScript(url, source, 0, 0); DART_CHECK_VALID(lib); result = Dart_SetNativeResolver(lib, resolver, NULL); DART_CHECK_VALID(result); if (finalize_classes) { result = Dart_FinalizeLoading(false); DART_CHECK_VALID(result); } return lib; } #ifndef PRODUCT void TestCase::SetReloadTestScript(const char* script) { if (script_reload_key == kUnsetThreadLocalKey) { script_reload_key = OSThread::CreateThreadLocal(); } ASSERT(script_reload_key != kUnsetThreadLocalKey); ASSERT(OSThread::GetThreadLocal(script_reload_key) == 0); // Store the new script in TLS. OSThread::SetThreadLocal(script_reload_key, reinterpret_cast<uword>(script)); } Dart_Handle TestCase::TriggerReload() { Isolate* isolate = Isolate::Current(); { TransitionNativeToVM transition(Thread::Current()); isolate->ReloadSources(/* test_mode = */ true); } return Dart_FinalizeLoading(false); } Dart_Handle TestCase::GetReloadErrorOrRootLibrary() { Isolate* isolate = Isolate::Current(); if (isolate->reload_context() != NULL) { // We should only have a reload context hanging around if an error occurred. ASSERT(isolate->reload_context()->has_error()); // Return a handle to the error. return Api::NewHandle(Thread::Current(), isolate->reload_context()->error()); } return Dart_RootLibrary(); } Dart_Handle TestCase::ReloadTestScript(const char* script) { SetReloadTestScript(script); Dart_Handle result = TriggerReload(); if (Dart_IsError(result)) { return result; } return GetReloadErrorOrRootLibrary(); } #endif // !PRODUCT Dart_Handle TestCase::LoadCoreTestScript(const char* script, Dart_NativeEntryResolver resolver) { return LoadTestScript(script, resolver, CORELIB_TEST_URI); } Dart_Handle TestCase::lib() { Dart_Handle url = NewString(TestCase::url()); Dart_Handle lib = Dart_LookupLibrary(url); DART_CHECK_VALID(lib); ASSERT(Dart_IsLibrary(lib)); return lib; } Dart_Handle TestCase::library_handler(Dart_LibraryTag tag, Dart_Handle library, Dart_Handle url) { if (tag == Dart_kCanonicalizeUrl) { return url; } return Api::Success(); } char* TestCase::BigintToHexValue(Dart_CObject* bigint) { return bin::CObject::BigintToHexValue(bigint); } void AssemblerTest::Assemble() { const String& function_name = String::ZoneHandle( Symbols::New(Thread::Current(), name_)); // We make a dummy script so that exception objects can be composed for // assembler instructions that do runtime calls, in particular on DBC. const char* kDummyScript = "assembler_test_dummy_function() {}"; const Script& script = Script::Handle(Script::New( function_name, String::Handle(String::New(kDummyScript)), RawScript::kSourceTag)); script.Tokenize(String::Handle()); const Library& lib = Library::Handle(Library::CoreLibrary()); const Class& cls = Class::ZoneHandle( Class::New(lib, function_name, script, TokenPosition::kMinSource)); Function& function = Function::ZoneHandle( Function::New(function_name, RawFunction::kRegularFunction, true, false, false, false, false, cls, TokenPosition::kMinSource)); code_ = Code::FinalizeCode(function, assembler_); code_.set_owner(function); code_.set_exception_handlers(Object::empty_exception_handlers()); if (FLAG_disassemble) { OS::Print("Code for test '%s' {\n", name_); const Instructions& instructions = Instructions::Handle(code_.instructions()); uword start = instructions.EntryPoint(); Disassembler::Disassemble(start, start + assembler_->CodeSize()); OS::Print("}\n"); } } CodeGenTest::CodeGenTest(const char* name) : function_(Function::ZoneHandle()), node_sequence_(new SequenceNode(TokenPosition::kMinSource, new LocalScope(NULL, 0, 0))), default_parameter_values_(new ZoneGrowableArray<const Instance*> ()) { ASSERT(name != NULL); const String& function_name = String::ZoneHandle( Symbols::New(Thread::Current(), name)); // Add function to a class and that class to the class dictionary so that // frame walking can be used. Library& lib = Library::Handle(Library::CoreLibrary()); const Class& cls = Class::ZoneHandle( Class::New(lib, function_name, Script::Handle(), TokenPosition::kMinSource)); function_ = Function::New( function_name, RawFunction::kRegularFunction, true, false, false, false, false, cls, TokenPosition::kMinSource); function_.set_result_type(Type::Handle(Type::DynamicType())); const Array& functions = Array::Handle(Array::New(1)); functions.SetAt(0, function_); cls.SetFunctions(functions); lib.AddClass(cls); } void CodeGenTest::Compile() { if (function_.HasCode()) return; ParsedFunction* parsed_function = new ParsedFunction(Thread::Current(), function_); parsed_function->SetNodeSequence(node_sequence_); parsed_function->set_instantiator(NULL); parsed_function->set_default_parameter_values(default_parameter_values_); node_sequence_->scope()->AddVariable( parsed_function->current_context_var()); parsed_function->EnsureExpressionTemp(); node_sequence_->scope()->AddVariable(parsed_function->expression_temp_var()); parsed_function->AllocateVariables(); const Error& error = Error::Handle(Compiler::CompileParsedFunction(parsed_function)); EXPECT(error.IsNull()); } bool CompilerTest::TestCompileScript(const Library& library, const Script& script) { Isolate* isolate = Isolate::Current(); ASSERT(isolate != NULL); const Error& error = Error::Handle(Compiler::Compile(library, script)); if (!error.IsNull()) { OS::Print("Error compiling test script:\n%s\n", error.ToErrorCString()); } return error.IsNull(); } bool CompilerTest::TestCompileFunction(const Function& function) { Thread* thread = Thread::Current(); ASSERT(thread != NULL); ASSERT(ClassFinalizer::AllClassesFinalized()); const Error& error = Error::Handle(Compiler::CompileFunction(thread, function)); return error.IsNull(); } void ElideJSONSubstring(const char* prefix, const char* in, char* out) { const char* pos = strstr(in, prefix); while (pos != NULL) { // Copy up to pos into the output buffer. while (in < pos) { *out++ = *in++; } // Skip to the close quote. in += strcspn(in, "\""); pos = strstr(in, prefix); } // Copy the remainder of in to out. while (*in != '\0') { *out++ = *in++; } *out = '\0'; } } // namespace dart <commit_msg>More ifndef PRODUCT.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/unit_test.h" #include <stdio.h> #include "bin/builtin.h" #include "bin/dartutils.h" #include "bin/isolate_data.h" #include "platform/globals.h" #include "vm/assembler.h" #include "vm/ast_printer.h" #include "vm/compiler.h" #include "vm/dart_api_impl.h" #include "vm/disassembler.h" #include "vm/isolate_reload.h" #include "vm/parser.h" #include "vm/symbols.h" #include "vm/thread.h" #include "vm/virtual_memory.h" using dart::bin::Builtin; using dart::bin::DartUtils; namespace dart { TestCaseBase* TestCaseBase::first_ = NULL; TestCaseBase* TestCaseBase::tail_ = NULL; TestCaseBase::TestCaseBase(const char* name) : next_(NULL), name_(name) { if (first_ == NULL) { first_ = this; } else { tail_->next_ = this; } tail_ = this; } void TestCaseBase::RunAll() { TestCaseBase* test = first_; while (test != NULL) { test->RunTest(); test = test->next_; } } Dart_Isolate TestCase::CreateIsolate(const uint8_t* buffer, const char* name) { bin::IsolateData* isolate_data = new bin::IsolateData(name, NULL, NULL); char* err; Dart_Isolate isolate = Dart_CreateIsolate( name, NULL, buffer, NULL, isolate_data, &err); if (isolate == NULL) { OS::Print("Creation of isolate failed '%s'\n", err); free(err); } EXPECT(isolate != NULL); return isolate; } static const char* kPackageScheme = "package:"; static bool IsPackageSchemeURL(const char* url_name) { static const intptr_t kPackageSchemeLen = strlen(kPackageScheme); return (strncmp(url_name, kPackageScheme, kPackageSchemeLen) == 0); } static bool IsImportableTestLib(const char* url_name) { const char* kImportTestLibUri = "test:importable_lib"; static const intptr_t kImportTestLibUriLen = strlen(kImportTestLibUri); return (strncmp(url_name, kImportTestLibUri, kImportTestLibUriLen) == 0); } static Dart_Handle ImportableTestLibSource() { const char* kScript = "importedFunc() => 'a';\n" "importedIntFunc() => 4;\n" "class ImportedMixin {\n" " mixinFunc() => 'mixin';\n" "}\n"; return DartUtils::NewString(kScript); } #ifndef PRODUCT static bool IsIsolateReloadTestLib(const char* url_name) { const char* kIsolateReloadTestLibUri = "test:isolate_reload_helper"; static const intptr_t kIsolateReloadTestLibUriLen = strlen(kIsolateReloadTestLibUri); return (strncmp(url_name, kIsolateReloadTestLibUri, kIsolateReloadTestLibUriLen) == 0); } static Dart_Handle IsolateReloadTestLibSource() { // Special library with one function. return DartUtils::NewString("void reloadTest() native 'Reload_Test';\n"); } static void ReloadTest(Dart_NativeArguments native_args) { DART_CHECK_VALID(TestCase::TriggerReload()); } static Dart_NativeFunction IsolateReloadTestNativeResolver( Dart_Handle name, int num_of_arguments, bool* auto_setup_scope) { return ReloadTest; } #endif // !PRODUCT static Dart_Handle ResolvePackageUri(const char* uri_chars) { const int kNumArgs = 1; Dart_Handle dart_args[kNumArgs]; dart_args[0] = DartUtils::NewString(uri_chars); return Dart_Invoke(DartUtils::BuiltinLib(), DartUtils::NewString("_filePathFromUri"), kNumArgs, dart_args); } static ThreadLocalKey script_reload_key = kUnsetThreadLocalKey; static Dart_Handle LibraryTagHandler(Dart_LibraryTag tag, Dart_Handle library, Dart_Handle url) { if (tag == Dart_kCanonicalizeUrl) { Dart_Handle library_url = Dart_LibraryUrl(library); if (Dart_IsError(library_url)) { return library_url; } return Dart_DefaultCanonicalizeUrl(library_url, url); } if (tag == Dart_kScriptTag) { // Reload request. ASSERT(script_reload_key != kUnsetThreadLocalKey); const char* script_source = reinterpret_cast<const char*>( OSThread::GetThreadLocal(script_reload_key)); ASSERT(script_source != NULL); OSThread::SetThreadLocal(script_reload_key, 0); return Dart_LoadScript(url, NewString(script_source), 0, 0); } if (!Dart_IsLibrary(library)) { return Dart_NewApiError("not a library"); } if (!Dart_IsString(url)) { return Dart_NewApiError("url is not a string"); } const char* url_chars = NULL; Dart_Handle result = Dart_StringToCString(url, &url_chars); if (Dart_IsError(result)) { return Dart_NewApiError("accessing url characters failed"); } Dart_Handle library_url = Dart_LibraryUrl(library); const char* library_url_string = NULL; result = Dart_StringToCString(library_url, &library_url_string); if (Dart_IsError(result)) { return result; } bool is_dart_scheme_url = DartUtils::IsDartSchemeURL(url_chars); bool is_io_library = DartUtils::IsDartIOLibURL(library_url_string); if (is_dart_scheme_url) { ASSERT(tag == Dart_kImportTag); // Handle imports of other built-in libraries present in the SDK. if (DartUtils::IsDartIOLibURL(url_chars)) { return Builtin::LoadAndCheckLibrary(Builtin::kIOLibrary); } else if (DartUtils::IsDartBuiltinLibURL(url_chars)) { return Builtin::LoadAndCheckLibrary(Builtin::kBuiltinLibrary); } else { return DartUtils::NewError("Do not know how to load '%s'", url_chars); } } if (IsImportableTestLib(url_chars)) { return Dart_LoadLibrary(url, ImportableTestLibSource(), 0, 0); } NOT_IN_PRODUCT( if (IsIsolateReloadTestLib(url_chars)) { Dart_Handle library = Dart_LoadLibrary(url, IsolateReloadTestLibSource(), 0, 0); DART_CHECK_VALID(library); Dart_SetNativeResolver(library, IsolateReloadTestNativeResolver, 0); return library; }) if (is_io_library) { ASSERT(tag == Dart_kSourceTag); return Dart_LoadSource(library, url, Builtin::PartSource(Builtin::kIOLibrary, url_chars), 0, 0); } if (IsPackageSchemeURL(url_chars)) { Dart_Handle resolved_uri = ResolvePackageUri(url_chars); DART_CHECK_VALID(resolved_uri); url_chars = NULL; Dart_Handle result = Dart_StringToCString(resolved_uri, &url_chars); if (Dart_IsError(result)) { return Dart_NewApiError("accessing url characters failed"); } } // Do sync loading since unit_test doesn't support async. Dart_Handle source = DartUtils::ReadStringFromFile(url_chars); EXPECT_VALID(source); if (tag == Dart_kImportTag) { return Dart_LoadLibrary(url, source, 0, 0); } else { ASSERT(tag == Dart_kSourceTag); return Dart_LoadSource(library, url, source, 0, 0); } } Dart_Handle TestCase::LoadTestScript(const char* script, Dart_NativeEntryResolver resolver, const char* lib_url, bool finalize_classes) { Dart_Handle url = NewString(lib_url); Dart_Handle source = NewString(script); Dart_Handle result = Dart_SetLibraryTagHandler(LibraryTagHandler); EXPECT_VALID(result); Dart_Handle lib = Dart_LoadScript(url, source, 0, 0); DART_CHECK_VALID(lib); result = Dart_SetNativeResolver(lib, resolver, NULL); DART_CHECK_VALID(result); if (finalize_classes) { result = Dart_FinalizeLoading(false); DART_CHECK_VALID(result); } return lib; } #ifndef PRODUCT void TestCase::SetReloadTestScript(const char* script) { if (script_reload_key == kUnsetThreadLocalKey) { script_reload_key = OSThread::CreateThreadLocal(); } ASSERT(script_reload_key != kUnsetThreadLocalKey); ASSERT(OSThread::GetThreadLocal(script_reload_key) == 0); // Store the new script in TLS. OSThread::SetThreadLocal(script_reload_key, reinterpret_cast<uword>(script)); } Dart_Handle TestCase::TriggerReload() { Isolate* isolate = Isolate::Current(); { TransitionNativeToVM transition(Thread::Current()); isolate->ReloadSources(/* test_mode = */ true); } return Dart_FinalizeLoading(false); } Dart_Handle TestCase::GetReloadErrorOrRootLibrary() { Isolate* isolate = Isolate::Current(); if (isolate->reload_context() != NULL) { // We should only have a reload context hanging around if an error occurred. ASSERT(isolate->reload_context()->has_error()); // Return a handle to the error. return Api::NewHandle(Thread::Current(), isolate->reload_context()->error()); } return Dart_RootLibrary(); } Dart_Handle TestCase::ReloadTestScript(const char* script) { SetReloadTestScript(script); Dart_Handle result = TriggerReload(); if (Dart_IsError(result)) { return result; } return GetReloadErrorOrRootLibrary(); } #endif // !PRODUCT Dart_Handle TestCase::LoadCoreTestScript(const char* script, Dart_NativeEntryResolver resolver) { return LoadTestScript(script, resolver, CORELIB_TEST_URI); } Dart_Handle TestCase::lib() { Dart_Handle url = NewString(TestCase::url()); Dart_Handle lib = Dart_LookupLibrary(url); DART_CHECK_VALID(lib); ASSERT(Dart_IsLibrary(lib)); return lib; } Dart_Handle TestCase::library_handler(Dart_LibraryTag tag, Dart_Handle library, Dart_Handle url) { if (tag == Dart_kCanonicalizeUrl) { return url; } return Api::Success(); } char* TestCase::BigintToHexValue(Dart_CObject* bigint) { return bin::CObject::BigintToHexValue(bigint); } void AssemblerTest::Assemble() { const String& function_name = String::ZoneHandle( Symbols::New(Thread::Current(), name_)); // We make a dummy script so that exception objects can be composed for // assembler instructions that do runtime calls, in particular on DBC. const char* kDummyScript = "assembler_test_dummy_function() {}"; const Script& script = Script::Handle(Script::New( function_name, String::Handle(String::New(kDummyScript)), RawScript::kSourceTag)); script.Tokenize(String::Handle()); const Library& lib = Library::Handle(Library::CoreLibrary()); const Class& cls = Class::ZoneHandle( Class::New(lib, function_name, script, TokenPosition::kMinSource)); Function& function = Function::ZoneHandle( Function::New(function_name, RawFunction::kRegularFunction, true, false, false, false, false, cls, TokenPosition::kMinSource)); code_ = Code::FinalizeCode(function, assembler_); code_.set_owner(function); code_.set_exception_handlers(Object::empty_exception_handlers()); #ifndef PRODUCT if (FLAG_disassemble) { OS::Print("Code for test '%s' {\n", name_); const Instructions& instructions = Instructions::Handle(code_.instructions()); uword start = instructions.EntryPoint(); Disassembler::Disassemble(start, start + assembler_->CodeSize()); OS::Print("}\n"); } #endif // !PRODUCT } CodeGenTest::CodeGenTest(const char* name) : function_(Function::ZoneHandle()), node_sequence_(new SequenceNode(TokenPosition::kMinSource, new LocalScope(NULL, 0, 0))), default_parameter_values_(new ZoneGrowableArray<const Instance*> ()) { ASSERT(name != NULL); const String& function_name = String::ZoneHandle( Symbols::New(Thread::Current(), name)); // Add function to a class and that class to the class dictionary so that // frame walking can be used. Library& lib = Library::Handle(Library::CoreLibrary()); const Class& cls = Class::ZoneHandle( Class::New(lib, function_name, Script::Handle(), TokenPosition::kMinSource)); function_ = Function::New( function_name, RawFunction::kRegularFunction, true, false, false, false, false, cls, TokenPosition::kMinSource); function_.set_result_type(Type::Handle(Type::DynamicType())); const Array& functions = Array::Handle(Array::New(1)); functions.SetAt(0, function_); cls.SetFunctions(functions); lib.AddClass(cls); } void CodeGenTest::Compile() { if (function_.HasCode()) return; ParsedFunction* parsed_function = new ParsedFunction(Thread::Current(), function_); parsed_function->SetNodeSequence(node_sequence_); parsed_function->set_instantiator(NULL); parsed_function->set_default_parameter_values(default_parameter_values_); node_sequence_->scope()->AddVariable( parsed_function->current_context_var()); parsed_function->EnsureExpressionTemp(); node_sequence_->scope()->AddVariable(parsed_function->expression_temp_var()); parsed_function->AllocateVariables(); const Error& error = Error::Handle(Compiler::CompileParsedFunction(parsed_function)); EXPECT(error.IsNull()); } bool CompilerTest::TestCompileScript(const Library& library, const Script& script) { Isolate* isolate = Isolate::Current(); ASSERT(isolate != NULL); const Error& error = Error::Handle(Compiler::Compile(library, script)); if (!error.IsNull()) { OS::Print("Error compiling test script:\n%s\n", error.ToErrorCString()); } return error.IsNull(); } bool CompilerTest::TestCompileFunction(const Function& function) { Thread* thread = Thread::Current(); ASSERT(thread != NULL); ASSERT(ClassFinalizer::AllClassesFinalized()); const Error& error = Error::Handle(Compiler::CompileFunction(thread, function)); return error.IsNull(); } void ElideJSONSubstring(const char* prefix, const char* in, char* out) { const char* pos = strstr(in, prefix); while (pos != NULL) { // Copy up to pos into the output buffer. while (in < pos) { *out++ = *in++; } // Skip to the close quote. in += strcspn(in, "\""); pos = strstr(in, prefix); } // Copy the remainder of in to out. while (*in != '\0') { *out++ = *in++; } *out = '\0'; } } // namespace dart <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <algorithm> #include <memory> #include "ngraph/runtime/aligned_buffer.hpp" #include "ngraph/runtime/allocator.hpp" #include "ngraph/util.hpp" using namespace ngraph; using namespace std; runtime::AlignedBuffer::AlignedBuffer() : m_allocator(nullptr) , m_allocated_buffer(nullptr) , m_aligned_buffer(nullptr) , m_byte_size(0) { } runtime::AlignedBuffer::AlignedBuffer(size_t byte_size, size_t alignment, Allocator* allocator) : m_allocator(allocator) , m_byte_size(byte_size) { m_byte_size = std::max<size_t>(1, byte_size); size_t allocation_size = m_byte_size + alignment; if (allocator) { m_allocated_buffer = static_cast<char*>(m_allocator->malloc(allocation_size, alignment)); } else { m_allocated_buffer = static_cast<char*>(malloc(allocation_size)); } m_aligned_buffer = m_allocated_buffer; size_t mod = size_t(m_aligned_buffer) % alignment; if (mod != 0) { m_aligned_buffer += (alignment - mod); } } runtime::AlignedBuffer::AlignedBuffer(AlignedBuffer&& other) : m_allocator(other.m_allocator) , m_allocated_buffer(other.m_allocated_buffer) , m_aligned_buffer(other.m_aligned_buffer) , m_byte_size(other.m_byte_size) { other.m_allocator = nullptr; other.m_allocated_buffer = nullptr; other.m_aligned_buffer = nullptr; other.m_byte_size = 0; } runtime::AlignedBuffer::~AlignedBuffer() { if (m_allocated_buffer != nullptr) { if (m_allocator) { m_allocator->free(m_allocated_buffer); } else { free(m_allocated_buffer); } } } runtime::AlignedBuffer& runtime::AlignedBuffer::operator=(AlignedBuffer&& other) { if (this != &other) { m_allocator = other.m_allocator; m_allocated_buffer = other.m_allocated_buffer; m_aligned_buffer = other.m_aligned_buffer; m_byte_size = other.m_byte_size; other.m_allocator = nullptr; other.m_allocated_buffer = nullptr; other.m_aligned_buffer = nullptr; other.m_byte_size = 0; } return *this; } <commit_msg>Call ngraph_malloc instead of malloc so it throws if out of memory (#3681)<commit_after>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <algorithm> #include <memory> #include "ngraph/runtime/aligned_buffer.hpp" #include "ngraph/runtime/allocator.hpp" #include "ngraph/util.hpp" using namespace ngraph; using namespace std; runtime::AlignedBuffer::AlignedBuffer() : m_allocator(nullptr) , m_allocated_buffer(nullptr) , m_aligned_buffer(nullptr) , m_byte_size(0) { } runtime::AlignedBuffer::AlignedBuffer(size_t byte_size, size_t alignment, Allocator* allocator) : m_allocator(allocator) , m_byte_size(byte_size) { m_byte_size = std::max<size_t>(1, byte_size); size_t allocation_size = m_byte_size + alignment; if (allocator) { m_allocated_buffer = static_cast<char*>(m_allocator->malloc(allocation_size, alignment)); } else { m_allocated_buffer = static_cast<char*>(ngraph_malloc(allocation_size)); } m_aligned_buffer = m_allocated_buffer; size_t mod = size_t(m_aligned_buffer) % alignment; if (mod != 0) { m_aligned_buffer += (alignment - mod); } } runtime::AlignedBuffer::AlignedBuffer(AlignedBuffer&& other) : m_allocator(other.m_allocator) , m_allocated_buffer(other.m_allocated_buffer) , m_aligned_buffer(other.m_aligned_buffer) , m_byte_size(other.m_byte_size) { other.m_allocator = nullptr; other.m_allocated_buffer = nullptr; other.m_aligned_buffer = nullptr; other.m_byte_size = 0; } runtime::AlignedBuffer::~AlignedBuffer() { if (m_allocated_buffer != nullptr) { if (m_allocator) { m_allocator->free(m_allocated_buffer); } else { free(m_allocated_buffer); } } } runtime::AlignedBuffer& runtime::AlignedBuffer::operator=(AlignedBuffer&& other) { if (this != &other) { m_allocator = other.m_allocator; m_allocated_buffer = other.m_allocated_buffer; m_aligned_buffer = other.m_aligned_buffer; m_byte_size = other.m_byte_size; other.m_allocator = nullptr; other.m_allocated_buffer = nullptr; other.m_aligned_buffer = nullptr; other.m_byte_size = 0; } return *this; } <|endoftext|>
<commit_before>// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "HistogramWidget.h" #include <absl/strings/str_cat.h> #include <absl/strings/str_format.h> #include <qnamespace.h> #include <qpoint.h> #include <QEvent> #include <QPainter> #include <QWidget> #include <algorithm> #include <cmath> #include <cstdint> #include <iterator> #include <string> #include <utility> #include "DisplayFormats/DisplayFormats.h" #include "Statistics/Histogram.h" constexpr double kRelativeMargin = 0.1; constexpr uint32_t kVerticalTickCount = 3; constexpr uint32_t kHorizontalTickCount = 3; constexpr int kTickLength = 5; [[nodiscard]] static int RoundToClosestInt(double x) { return static_cast<int>(std::round(x)); } [[nodiscard]] static int Width(const QPainter& painter) { return painter.device()->width(); } [[nodiscard]] static int WidthMargin(const QPainter& painter) { return RoundToClosestInt(Width(painter) * kRelativeMargin); } [[nodiscard]] static int Height(const QPainter& painter) { return painter.device()->height(); } [[nodiscard]] static int HeightMargin(const QPainter& painter) { return RoundToClosestInt(Height(painter) * kRelativeMargin); } // if `length > 0`, the line will be plot to the right from `start` and to the left otherwise static void DrawHorizontalLine(QPainter& painter, const QPoint& start, int length) { painter.drawLine(start, {start.x() + length, start.y()}); } // if `length > 0`, the line will be plot downwards from `start` and upwards otherwise static void DrawVerticalLine(QPainter& painter, const QPoint& start, int length) { painter.drawLine(start, {start.x(), start.y() + length}); } static void DrawHorizontalAxis(QPainter& painter, const QPoint& axes_intersection, const orbit_statistics::Histogram& histogram, int length) { DrawHorizontalLine(painter, axes_intersection, length); const int tick_spacing_as_value = RoundToClosestInt(static_cast<double>(histogram.max) / kHorizontalTickCount); const int tick_spacing_pixels = RoundToClosestInt(static_cast<double>(length) / kHorizontalTickCount); int current_tick_location = tick_spacing_pixels + axes_intersection.x(); int current_tick_value = tick_spacing_as_value; const QFontMetrics font_metrics(painter.font()); for (uint32_t i = 1; i <= kHorizontalTickCount; ++i) { DrawVerticalLine(painter, {current_tick_location, axes_intersection.y()}, kTickLength); const QString tick_label = QString::fromStdString( orbit_display_formats::GetDisplayTime(absl::Nanoseconds(current_tick_value))); const QRect tick_label_bounding_rect = font_metrics.boundingRect(tick_label); painter.drawText(current_tick_location - tick_label_bounding_rect.width() / 2, axes_intersection.y() + kTickLength + tick_label_bounding_rect.height(), tick_label); current_tick_location += tick_spacing_pixels; current_tick_value += tick_spacing_as_value; } } static void DrawVerticalAxis(QPainter& painter, const QPoint& axes_intersection, int length, double max_freq) { DrawVerticalLine(painter, axes_intersection, -length); const double tick_spacing_as_value = max_freq / kVerticalTickCount; const int tick_spacing_pixels = RoundToClosestInt(static_cast<double>(length) / kVerticalTickCount); double current_tick_value = tick_spacing_as_value; int current_tick_location = axes_intersection.y() - tick_spacing_pixels; const QFontMetrics font_metrics(painter.font()); for (uint32_t i = 1; i <= kVerticalTickCount; ++i) { DrawHorizontalLine(painter, {axes_intersection.x(), current_tick_location}, -kTickLength); QString tick_label = QString::fromStdString(absl::StrFormat("%.2f", current_tick_value)); QRect tick_label_bounding_rect = font_metrics.boundingRect(tick_label); painter.drawText(axes_intersection.x() - tick_label_bounding_rect.width() - kTickLength, current_tick_location + tick_label_bounding_rect.height() / 2, tick_label); current_tick_location -= tick_spacing_pixels; current_tick_value += tick_spacing_as_value; } } [[nodiscard]] static int ValueToAxisLocation(double value, int axis_length, double max_value) { return RoundToClosestInt((value / max_value) * axis_length); } [[nodiscard]] static double GetFreq(const orbit_statistics::Histogram& histogram, size_t i) { return static_cast<double>(histogram.counts[i]) / static_cast<double>(histogram.data_set_size); } static void DrawHistogram(QPainter& painter, const QPoint& axes_intersection, const orbit_statistics::Histogram& histogram, int horizontal_axis_length, int vertical_axis_length, double max_freq, int vertical_shift) { for (size_t i = 0; i < histogram.counts.size(); ++i) { const uint64_t bin_from = histogram.min + i * histogram.bin_width; const uint64_t bin_to = bin_from + histogram.bin_width; double freq = GetFreq(histogram, i); if (freq > 0) { const QPoint top_left( axes_intersection.x() + ValueToAxisLocation(bin_from, horizontal_axis_length, histogram.max), axes_intersection.y() - vertical_shift - ValueToAxisLocation(freq, vertical_axis_length, max_freq)); const QPoint lower_right( axes_intersection.x() + ValueToAxisLocation(bin_to, horizontal_axis_length, histogram.max), axes_intersection.y() - vertical_shift); const QRect bar(top_left, lower_right); painter.fillRect(bar, Qt::cyan); } } } void HistogramWidget::UpdateHistogram(std::optional<orbit_statistics::Histogram> histogram, std::string function_name) { histogram_ = std::move(histogram); function_name_ = std::move(function_name); update(); } static void DrawTitle(const std::string& text, QPainter& painter) { const QFontMetrics font_metrics(painter.font()); const QString qtext = QString::fromStdString(text); const QRect title_bounding_rect = font_metrics.boundingRect(qtext); painter.drawText((painter.device()->width() - title_bounding_rect.width()) / 2, title_bounding_rect.height(), qtext); } void HistogramWidget::paintEvent(QPaintEvent* /*event*/) { QPainter painter(this); if (!histogram_) { DrawTitle("Select a function with Count>0 to plot a histogram of its runtime", painter); return; } const int axis_width = painter.pen().width(); const int width = painter.device()->width(); const int height = painter.device()->height(); QPoint axes_intersection(RoundToClosestInt(width * kRelativeMargin), RoundToClosestInt(height * (1 - kRelativeMargin))); const int vertical_axis_length = Height(painter) - 2 * HeightMargin(painter); const int horizontal_axis_length = Width(painter) - 2 * WidthMargin(painter); const uint64_t max_count = *std::max_element(std::begin(histogram_->counts), std::end(histogram_->counts)); const double max_freq = static_cast<double>(max_count) / histogram_->data_set_size; DrawHistogram(painter, axes_intersection, histogram_.value(), horizontal_axis_length, vertical_axis_length, max_freq, axis_width); DrawHorizontalAxis(painter, axes_intersection, histogram_.value(), horizontal_axis_length); DrawVerticalAxis(painter, axes_intersection, vertical_axis_length, max_freq); DrawTitle(function_name_.value(), painter); }<commit_msg>Use uint64_t to store nanoseconds (#3364)<commit_after>// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "HistogramWidget.h" #include <absl/strings/str_cat.h> #include <absl/strings/str_format.h> #include <qnamespace.h> #include <qpoint.h> #include <QEvent> #include <QPainter> #include <QWidget> #include <algorithm> #include <cmath> #include <cstdint> #include <iterator> #include <string> #include <utility> #include "DisplayFormats/DisplayFormats.h" #include "Statistics/Histogram.h" constexpr double kRelativeMargin = 0.1; constexpr uint32_t kVerticalTickCount = 3; constexpr uint32_t kHorizontalTickCount = 3; constexpr int kTickLength = 5; [[nodiscard]] static int RoundToClosestInt(double x) { return static_cast<int>(std::round(x)); } [[nodiscard]] static int Width(const QPainter& painter) { return painter.device()->width(); } [[nodiscard]] static int WidthMargin(const QPainter& painter) { return RoundToClosestInt(Width(painter) * kRelativeMargin); } [[nodiscard]] static int Height(const QPainter& painter) { return painter.device()->height(); } [[nodiscard]] static int HeightMargin(const QPainter& painter) { return RoundToClosestInt(Height(painter) * kRelativeMargin); } // if `length > 0`, the line will be plot to the right from `start` and to the left otherwise static void DrawHorizontalLine(QPainter& painter, const QPoint& start, int length) { painter.drawLine(start, {start.x() + length, start.y()}); } // if `length > 0`, the line will be plot downwards from `start` and upwards otherwise static void DrawVerticalLine(QPainter& painter, const QPoint& start, int length) { painter.drawLine(start, {start.x(), start.y() + length}); } static void DrawHorizontalAxis(QPainter& painter, const QPoint& axes_intersection, const orbit_statistics::Histogram& histogram, int length) { DrawHorizontalLine(painter, axes_intersection, length); const auto tick_spacing_as_value = static_cast<uint64_t>(static_cast<double>(histogram.max) / kHorizontalTickCount); const int tick_spacing_pixels = RoundToClosestInt(static_cast<double>(length) / kHorizontalTickCount); int current_tick_location = tick_spacing_pixels + axes_intersection.x(); uint64_t current_tick_value = tick_spacing_as_value; const QFontMetrics font_metrics(painter.font()); for (uint32_t i = 1; i <= kHorizontalTickCount; ++i) { DrawVerticalLine(painter, {current_tick_location, axes_intersection.y()}, kTickLength); const QString tick_label = QString::fromStdString( orbit_display_formats::GetDisplayTime(absl::Nanoseconds(current_tick_value))); const QRect tick_label_bounding_rect = font_metrics.boundingRect(tick_label); painter.drawText(current_tick_location - tick_label_bounding_rect.width() / 2, axes_intersection.y() + kTickLength + tick_label_bounding_rect.height(), tick_label); current_tick_location += tick_spacing_pixels; current_tick_value += tick_spacing_as_value; } } static void DrawVerticalAxis(QPainter& painter, const QPoint& axes_intersection, int length, double max_freq) { DrawVerticalLine(painter, axes_intersection, -length); const double tick_spacing_as_value = max_freq / kVerticalTickCount; const int tick_spacing_pixels = RoundToClosestInt(static_cast<double>(length) / kVerticalTickCount); double current_tick_value = tick_spacing_as_value; int current_tick_location = axes_intersection.y() - tick_spacing_pixels; const QFontMetrics font_metrics(painter.font()); for (uint32_t i = 1; i <= kVerticalTickCount; ++i) { DrawHorizontalLine(painter, {axes_intersection.x(), current_tick_location}, -kTickLength); QString tick_label = QString::fromStdString(absl::StrFormat("%.2f", current_tick_value)); QRect tick_label_bounding_rect = font_metrics.boundingRect(tick_label); painter.drawText(axes_intersection.x() - tick_label_bounding_rect.width() - kTickLength, current_tick_location + tick_label_bounding_rect.height() / 2, tick_label); current_tick_location -= tick_spacing_pixels; current_tick_value += tick_spacing_as_value; } } [[nodiscard]] static int ValueToAxisLocation(double value, int axis_length, double max_value) { return RoundToClosestInt((value / max_value) * axis_length); } [[nodiscard]] static double GetFreq(const orbit_statistics::Histogram& histogram, size_t i) { return static_cast<double>(histogram.counts[i]) / static_cast<double>(histogram.data_set_size); } static void DrawHistogram(QPainter& painter, const QPoint& axes_intersection, const orbit_statistics::Histogram& histogram, int horizontal_axis_length, int vertical_axis_length, double max_freq, int vertical_shift) { for (size_t i = 0; i < histogram.counts.size(); ++i) { const uint64_t bin_from = histogram.min + i * histogram.bin_width; const uint64_t bin_to = bin_from + histogram.bin_width; double freq = GetFreq(histogram, i); if (freq > 0) { const QPoint top_left( axes_intersection.x() + ValueToAxisLocation(bin_from, horizontal_axis_length, histogram.max), axes_intersection.y() - vertical_shift - ValueToAxisLocation(freq, vertical_axis_length, max_freq)); const QPoint lower_right( axes_intersection.x() + ValueToAxisLocation(bin_to, horizontal_axis_length, histogram.max), axes_intersection.y() - vertical_shift); const QRect bar(top_left, lower_right); painter.fillRect(bar, Qt::cyan); } } } void HistogramWidget::UpdateHistogram(std::optional<orbit_statistics::Histogram> histogram, std::string function_name) { histogram_ = std::move(histogram); function_name_ = std::move(function_name); update(); } static void DrawTitle(const std::string& text, QPainter& painter) { const QFontMetrics font_metrics(painter.font()); const QString qtext = QString::fromStdString(text); const QRect title_bounding_rect = font_metrics.boundingRect(qtext); painter.drawText((painter.device()->width() - title_bounding_rect.width()) / 2, title_bounding_rect.height(), qtext); } void HistogramWidget::paintEvent(QPaintEvent* /*event*/) { QPainter painter(this); if (!histogram_) { DrawTitle("Select a function with Count>0 to plot a histogram of its runtime", painter); return; } const int axis_width = painter.pen().width(); const int width = painter.device()->width(); const int height = painter.device()->height(); QPoint axes_intersection(RoundToClosestInt(width * kRelativeMargin), RoundToClosestInt(height * (1 - kRelativeMargin))); const int vertical_axis_length = Height(painter) - 2 * HeightMargin(painter); const int horizontal_axis_length = Width(painter) - 2 * WidthMargin(painter); const uint64_t max_count = *std::max_element(std::begin(histogram_->counts), std::end(histogram_->counts)); const double max_freq = static_cast<double>(max_count) / histogram_->data_set_size; DrawHistogram(painter, axes_intersection, histogram_.value(), horizontal_axis_length, vertical_axis_length, max_freq, axis_width); DrawHorizontalAxis(painter, axes_intersection, histogram_.value(), horizontal_axis_length); DrawVerticalAxis(painter, axes_intersection, vertical_axis_length, max_freq); DrawTitle(function_name_.value(), painter); }<|endoftext|>
<commit_before> #ifndef RESOURCE_PACKER_INTERNAL_HPP #define RESOURCE_PACKER_INTERNAL_HPP #include <iostream> namespace RP { bool isLittleEndian(); template <typename T> void writeLittleEndian(std::ofstream& o, T data) { union { T i; char c[sizeof(T)]; } bint; bint.i = data; if(!isLittleEndian() && sizeof(T) > 1) { char s; for(unsigned int i = 0; i < sizeof(T) / 2; ++i) { s = bint.c[i]; bint.c[i] = bint.c[sizeof(T) - 1 - i]; bint.c[sizeof(T) - 1 - i] = s; } } o.write((char*) &bint.i, sizeof(T)); } template <typename T> T readLittleEndian(std::ifstream& i) { union { T i; char c[sizeof(T)]; } bint; i.read((char*) &bint.i, sizeof(T)); if(!isLittleEndian()) { char s; for(unsigned int i = 0; i < sizeof(T) / 2; ++i) { s = bint.c[i]; bint.c[i] = bint.c[sizeof(T) - 1 - i]; bint.c[sizeof(T) - 1 - i] = s; } } return bint.i; } } #endif <commit_msg>Minor fix<commit_after> #ifndef RESOURCE_PACKER_INTERNAL_HPP #define RESOURCE_PACKER_INTERNAL_HPP #include <iostream> namespace RP { bool isLittleEndian(); template <typename T> void writeLittleEndian(std::ofstream& o, T data) { union { T i; char c[sizeof(T)]; } bint; bint.i = data; if(!isLittleEndian() && sizeof(T) > 1) { char s; for(unsigned int i = 0; i < sizeof(T) / 2; ++i) { s = bint.c[i]; bint.c[i] = bint.c[sizeof(T) - 1 - i]; bint.c[sizeof(T) - 1 - i] = s; } } o.write((char*) &bint.i, sizeof(T)); } template <typename T> T readLittleEndian(std::ifstream& i) { union { T i; char c[sizeof(T)]; } bint; i.read((char*) &bint.i, sizeof(T)); if(!isLittleEndian() && sizeof(T) > 1) { char s; for(unsigned int i = 0; i < sizeof(T) / 2; ++i) { s = bint.c[i]; bint.c[i] = bint.c[sizeof(T) - 1 - i]; bint.c[sizeof(T) - 1 - i] = s; } } return bint.i; } } #endif <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2016 xiongziliang <[email protected]> * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "H264RtmpCodec.h" namespace mediakit{ H264RtmpDecoder::H264RtmpDecoder() { _h264frame = obtainFrame(); } H264Frame::Ptr H264RtmpDecoder::obtainFrame() { //从缓存池重新申请对象,防止覆盖已经写入环形缓存的对象 auto frame = obtainObj(); frame->buffer.clear(); frame->iPrefixSize = 4; return frame; } bool H264RtmpDecoder::inputRtmp(const RtmpPacket::Ptr &rtmp, bool key_pos) { key_pos = decodeRtmp(rtmp); RtmpCodec::inputRtmp(rtmp, key_pos); return key_pos; } bool H264RtmpDecoder::decodeRtmp(const RtmpPacket::Ptr &pkt) { if (pkt->isCfgFrame()) { //缓存sps pps,后续插入到I帧之前 _sps = pkt->getH264SPS(); _pps = pkt->getH264PPS(); return false; } if (_sps.size()) { uint32_t iTotalLen = pkt->strBuf.size(); uint32_t iOffset = 5; while(iOffset + 4 < iTotalLen){ uint32_t iFrameLen; memcpy(&iFrameLen, pkt->strBuf.data() + iOffset, 4); iFrameLen = ntohl(iFrameLen); iOffset += 4; if(iFrameLen + iOffset > iTotalLen){ break; } onGetH264_l(pkt->strBuf.data() + iOffset, iFrameLen, pkt->timeStamp); iOffset += iFrameLen; } } return pkt->isVideoKeyFrame(); } inline void H264RtmpDecoder::onGetH264_l(const char* pcData, int iLen, uint32_t ui32TimeStamp) { switch (H264_TYPE(pcData[0])) { case H264Frame::NAL_IDR: { //I frame onGetH264(_sps.data(), _sps.length(), ui32TimeStamp); onGetH264(_pps.data(), _pps.length(), ui32TimeStamp); } case H264Frame::NAL_B_P: { //I or P or B frame onGetH264(pcData, iLen, ui32TimeStamp); } break; default: break; } } inline void H264RtmpDecoder::onGetH264(const char* pcData, int iLen, uint32_t ui32TimeStamp) { _h264frame->type = H264_TYPE(pcData[0]); _h264frame->timeStamp = ui32TimeStamp; _h264frame->buffer.assign("\x0\x0\x0\x1", 4); //添加264头 _h264frame->buffer.append(pcData, iLen); //写入环形缓存 RtmpCodec::inputFrame(_h264frame); _h264frame = obtainFrame(); } //////////////////////////////////////////////////////////////////////// H264RtmpEncoder::H264RtmpEncoder(const Track::Ptr &track) { _track = dynamic_pointer_cast<H264Track>(track); } void H264RtmpEncoder::inputFrame(const Frame::Ptr &frame) { RtmpCodec::inputFrame(frame); auto pcData = frame->data() + frame->prefixSize(); auto iLen = frame->size() - frame->prefixSize(); auto type = H264_TYPE(((uint8_t*)pcData)[0]); if(!_gotSpsPps){ //尝试从frame中获取sps pps switch (type){ case H264Frame::NAL_SPS:{ //sps if(_sps.empty()){ _sps = string(pcData,iLen); if(!_pps.empty()){ makeVideoConfigPkt(); } } } break; case H264Frame::NAL_PPS:{ //pps if(_pps.empty()){ _pps = string(pcData,iLen); if(!_sps.empty()){ makeVideoConfigPkt(); } } } break; default: break; } //尝试从track中获取sps pps信息 if((!_sps.empty() || !_pps.empty()) && _track && _track->ready()){ _sps = _track->getSps(); _pps = _track->getPps(); makeVideoConfigPkt(); } } switch (type){ case H264Frame::NAL_IDR: case H264Frame::NAL_B_P:{ if(_lastPacket && _lastPacket->timeStamp != frame->stamp()) { RtmpCodec::inputRtmp(_lastPacket, _lastPacket->isVideoKeyFrame()); _lastPacket = nullptr; } if(!_lastPacket) { //I or P or B frame int8_t flags = 7; //h.264 bool is_config = false; flags |= ((frame->keyFrame() ? FLV_KEY_FRAME : FLV_INTER_FRAME) << 4); _lastPacket = ResourcePoolHelper<RtmpPacket>::obtainObj(); _lastPacket->strBuf.clear(); _lastPacket->strBuf.push_back(flags); _lastPacket->strBuf.push_back(!is_config); _lastPacket->strBuf.append("\x0\x0\x0", 3); _lastPacket->chunkId = CHUNK_VIDEO; _lastPacket->streamId = STREAM_MEDIA; _lastPacket->timeStamp = frame->stamp(); _lastPacket->typeId = MSG_VIDEO; } auto size = htonl(iLen); _lastPacket->strBuf.append((char *) &size, 4); _lastPacket->strBuf.append(pcData, iLen); _lastPacket->bodySize = _lastPacket->strBuf.size(); } break; default: break; } } void H264RtmpEncoder::makeVideoConfigPkt() { _gotSpsPps = true; int8_t flags = 7; //h.264 flags |= (FLV_KEY_FRAME << 4); bool is_config = true; RtmpPacket::Ptr rtmpPkt = ResourcePoolHelper<RtmpPacket>::obtainObj(); rtmpPkt->strBuf.clear(); //////////header rtmpPkt->strBuf.push_back(flags); rtmpPkt->strBuf.push_back(!is_config); rtmpPkt->strBuf.append("\x0\x0\x0", 3); ////////////sps rtmpPkt->strBuf.push_back(1); // version //DebugL<<hexdump(_sps.data(), _sps.size()); rtmpPkt->strBuf.push_back(_sps[1]); // profile rtmpPkt->strBuf.push_back(_sps[2]); // compat rtmpPkt->strBuf.push_back(_sps[3]); // level rtmpPkt->strBuf.push_back(0xff); // 6 bits reserved + 2 bits nal size length - 1 (11) rtmpPkt->strBuf.push_back(0xe1); // 3 bits reserved + 5 bits number of sps (00001) uint16_t size = _sps.size(); size = htons(size); rtmpPkt->strBuf.append((char *) &size, 2); rtmpPkt->strBuf.append(_sps); /////////////pps rtmpPkt->strBuf.push_back(1); // version size = _pps.size(); size = htons(size); rtmpPkt->strBuf.append((char *) &size, 2); rtmpPkt->strBuf.append(_pps); rtmpPkt->bodySize = rtmpPkt->strBuf.size(); rtmpPkt->chunkId = CHUNK_VIDEO; rtmpPkt->streamId = STREAM_MEDIA; rtmpPkt->timeStamp = 0; rtmpPkt->typeId = MSG_VIDEO; RtmpCodec::inputRtmp(rtmpPkt, false); } }//namespace mediakit <commit_msg>优化rtmp注册速度<commit_after>/* * MIT License * * Copyright (c) 2016 xiongziliang <[email protected]> * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "H264RtmpCodec.h" namespace mediakit{ H264RtmpDecoder::H264RtmpDecoder() { _h264frame = obtainFrame(); } H264Frame::Ptr H264RtmpDecoder::obtainFrame() { //从缓存池重新申请对象,防止覆盖已经写入环形缓存的对象 auto frame = obtainObj(); frame->buffer.clear(); frame->iPrefixSize = 4; return frame; } bool H264RtmpDecoder::inputRtmp(const RtmpPacket::Ptr &rtmp, bool key_pos) { key_pos = decodeRtmp(rtmp); RtmpCodec::inputRtmp(rtmp, key_pos); return key_pos; } bool H264RtmpDecoder::decodeRtmp(const RtmpPacket::Ptr &pkt) { if (pkt->isCfgFrame()) { //缓存sps pps,后续插入到I帧之前 _sps = pkt->getH264SPS(); _pps = pkt->getH264PPS(); return false; } if (_sps.size()) { uint32_t iTotalLen = pkt->strBuf.size(); uint32_t iOffset = 5; while(iOffset + 4 < iTotalLen){ uint32_t iFrameLen; memcpy(&iFrameLen, pkt->strBuf.data() + iOffset, 4); iFrameLen = ntohl(iFrameLen); iOffset += 4; if(iFrameLen + iOffset > iTotalLen){ break; } onGetH264_l(pkt->strBuf.data() + iOffset, iFrameLen, pkt->timeStamp); iOffset += iFrameLen; } } return pkt->isVideoKeyFrame(); } inline void H264RtmpDecoder::onGetH264_l(const char* pcData, int iLen, uint32_t ui32TimeStamp) { switch (H264_TYPE(pcData[0])) { case H264Frame::NAL_IDR: { //I frame onGetH264(_sps.data(), _sps.length(), ui32TimeStamp); onGetH264(_pps.data(), _pps.length(), ui32TimeStamp); } case H264Frame::NAL_B_P: { //I or P or B frame onGetH264(pcData, iLen, ui32TimeStamp); } break; default: break; } } inline void H264RtmpDecoder::onGetH264(const char* pcData, int iLen, uint32_t ui32TimeStamp) { _h264frame->type = H264_TYPE(pcData[0]); _h264frame->timeStamp = ui32TimeStamp; _h264frame->buffer.assign("\x0\x0\x0\x1", 4); //添加264头 _h264frame->buffer.append(pcData, iLen); //写入环形缓存 RtmpCodec::inputFrame(_h264frame); _h264frame = obtainFrame(); } //////////////////////////////////////////////////////////////////////// H264RtmpEncoder::H264RtmpEncoder(const Track::Ptr &track) { _track = dynamic_pointer_cast<H264Track>(track); } void H264RtmpEncoder::inputFrame(const Frame::Ptr &frame) { RtmpCodec::inputFrame(frame); auto pcData = frame->data() + frame->prefixSize(); auto iLen = frame->size() - frame->prefixSize(); auto type = H264_TYPE(((uint8_t*)pcData)[0]); if(!_gotSpsPps){ //尝试从frame中获取sps pps switch (type){ case H264Frame::NAL_SPS:{ //sps if(_sps.empty()){ _sps = string(pcData,iLen); } } break; case H264Frame::NAL_PPS:{ //pps if(_pps.empty()){ _pps = string(pcData,iLen); } } break; default: break; } if(_track && _track->ready()){ //尝试从track中获取sps pps信息 _sps = _track->getSps(); _pps = _track->getPps(); } if(!_sps.empty() && !_pps.empty()){ _gotSpsPps = true; makeVideoConfigPkt(); } } switch (type){ case H264Frame::NAL_IDR: case H264Frame::NAL_B_P:{ if(_lastPacket && _lastPacket->timeStamp != frame->stamp()) { RtmpCodec::inputRtmp(_lastPacket, _lastPacket->isVideoKeyFrame()); _lastPacket = nullptr; } if(!_lastPacket) { //I or P or B frame int8_t flags = 7; //h.264 bool is_config = false; flags |= ((frame->keyFrame() ? FLV_KEY_FRAME : FLV_INTER_FRAME) << 4); _lastPacket = ResourcePoolHelper<RtmpPacket>::obtainObj(); _lastPacket->strBuf.clear(); _lastPacket->strBuf.push_back(flags); _lastPacket->strBuf.push_back(!is_config); _lastPacket->strBuf.append("\x0\x0\x0", 3); _lastPacket->chunkId = CHUNK_VIDEO; _lastPacket->streamId = STREAM_MEDIA; _lastPacket->timeStamp = frame->stamp(); _lastPacket->typeId = MSG_VIDEO; } auto size = htonl(iLen); _lastPacket->strBuf.append((char *) &size, 4); _lastPacket->strBuf.append(pcData, iLen); _lastPacket->bodySize = _lastPacket->strBuf.size(); } break; default: break; } } void H264RtmpEncoder::makeVideoConfigPkt() { int8_t flags = 7; //h.264 flags |= (FLV_KEY_FRAME << 4); bool is_config = true; RtmpPacket::Ptr rtmpPkt = ResourcePoolHelper<RtmpPacket>::obtainObj(); rtmpPkt->strBuf.clear(); //////////header rtmpPkt->strBuf.push_back(flags); rtmpPkt->strBuf.push_back(!is_config); rtmpPkt->strBuf.append("\x0\x0\x0", 3); ////////////sps rtmpPkt->strBuf.push_back(1); // version //DebugL<<hexdump(_sps.data(), _sps.size()); rtmpPkt->strBuf.push_back(_sps[1]); // profile rtmpPkt->strBuf.push_back(_sps[2]); // compat rtmpPkt->strBuf.push_back(_sps[3]); // level rtmpPkt->strBuf.push_back(0xff); // 6 bits reserved + 2 bits nal size length - 1 (11) rtmpPkt->strBuf.push_back(0xe1); // 3 bits reserved + 5 bits number of sps (00001) uint16_t size = _sps.size(); size = htons(size); rtmpPkt->strBuf.append((char *) &size, 2); rtmpPkt->strBuf.append(_sps); /////////////pps rtmpPkt->strBuf.push_back(1); // version size = _pps.size(); size = htons(size); rtmpPkt->strBuf.append((char *) &size, 2); rtmpPkt->strBuf.append(_pps); rtmpPkt->bodySize = rtmpPkt->strBuf.size(); rtmpPkt->chunkId = CHUNK_VIDEO; rtmpPkt->streamId = STREAM_MEDIA; rtmpPkt->timeStamp = 0; rtmpPkt->typeId = MSG_VIDEO; RtmpCodec::inputRtmp(rtmpPkt, false); } }//namespace mediakit <|endoftext|>
<commit_before>/// @file wlog_tools.cpp /// @brief Well Logs manipulation algorithms /// @author uentity /// @version 1.0 /// @date 27.02.2014 /// @copyright This source code is released under the terms of /// the BSD License. See LICENSE for more details. #ifndef WLOG_TOOLS_TMEEHO84 #define WLOG_TOOLS_TMEEHO84 #include "bs_kernel.h" #include "conf.h" #include <limits> // DEBUG //#include <iostream> namespace blue_sky { // hidden implementation namespace { typedef v_float::iterator vf_iterator; typedef v_float::const_iterator cvf_iterator; typedef v_float::reverse_iterator vf_riterator; typedef v_float::const_reverse_iterator cvf_riterator; // depth and share same iterator type template< class data_iterator, class grid_iterator, class res_iterator > void projection_impl( //const spv_float& wlog_data, const spv_float& wlog_dept, const data_iterator& p_data_begin, const data_iterator& p_data_end, const data_iterator& p_dept_begin, const data_iterator& p_dept_end, grid_iterator& p_grid, const grid_iterator& p_grid_end, res_iterator& p_res ) { // setup iterators //const cvf_iterator p_dept_begin = wlog_dept->begin(); //const cvf_iterator p_dept_end = p_dept_begin + wlog_sz; const ulong wlog_sz = std::min< ulong >(p_data_end - p_data_begin, p_dept_end - p_dept_begin); //const ulong wlog_sz = std::min(wlog_data->size(), wlog_dept->size()); if(wlog_sz == 0) return; // find starting point on well log data_iterator p_dept = std::lower_bound( p_dept_begin, p_dept_end, *p_grid ); if(p_dept == p_dept_end) // grid is fully outside of well log depths return; data_iterator p_data = p_data_begin + (p_dept - p_dept_begin); // DEBUG //std::cout << "++wlog_mean_projection:" << std::endl; //std::cout << "log_dept = [" << *p_dept << ", " << *(p_dept_end - 1) << "]" << std::endl; //std::cout << "grid = [" << *p_grid << ", " << *(p_grid_end - 1) << "]" << std::endl; // position dest grid to next boundary ++p_grid; const res_iterator p_res_end = p_res + (p_grid_end - p_grid - 1); // main cycle t_float win_sum = 0; // win_sz counts only valid numbers that fits in window // raw_sz counts all values in window, including NaNs ulong win_sz = 0, raw_sz = 0; while(p_grid != p_grid_end) { // if we reached window boundary if(*p_dept > *p_grid) { if(win_sz) *p_res = win_sum / win_sz; else if(!raw_sz && (p_dept != p_dept_begin)) { // assign prev log value only if we had no NaNs in window *p_res = *(p_data - 1); } // next step on dest grid and resulting array if(++p_res == p_res_end) break; ++p_grid; win_sum = 0; win_sz = 0; raw_sz = 0; } else { // we're inside window // check for NaN if(!(*p_data != *p_data)) { win_sum += *p_data; ++win_sz; } // count all values in raw_sz ++raw_sz; // next step in well log ++p_data; ++p_dept; if(p_dept == p_dept_end) { if(win_sz) *p_res = win_sum / win_sz; break; } } } } } // eof hidden namespace BS_API_PLUGIN spv_float wlog_mean_projection( spv_float wlog_data, spv_float wlog_dept, spv_float dest_grid ) { // sanity spv_float res = BS_KERNEL.create_object(v_float::bs_type()); if(!wlog_data->size() || !wlog_dept->size() || dest_grid->size() < 2 || !res) return res; res->resize(dest_grid->size() - 1); // fill resulting array with NaN std::fill(res->begin(), res->end(), std::numeric_limits< double >::quiet_NaN()); // check grid ordering if(dest_grid->ss(0) < dest_grid->ss(dest_grid->size() - 1)) { // normal ordering cvf_iterator p_grid = dest_grid->begin(); const cvf_iterator p_grid_end = dest_grid->end(); vf_iterator p_res = res->begin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } } else { // reversed grid ordering cvf_riterator p_grid = dest_grid->rbegin(); const cvf_riterator p_grid_end = dest_grid->rend(); vf_riterator p_res = res->rbegin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } //projection_impl(wlog_data, wlog_dept, p_grid, p_grid_end, p_res); } return res; } } /* namespace blue_sky */ #endif /* end of include guard: WLOG_TOOLS_TMEEHO84 */ <commit_msg>wlog_mean_peojection: fix NaN in very last layer (wrong resulting boundary calculation)<commit_after>/// @file wlog_tools.cpp /// @brief Well Logs manipulation algorithms /// @author uentity /// @version 1.0 /// @date 27.02.2014 /// @copyright This source code is released under the terms of /// the BSD License. See LICENSE for more details. #ifndef WLOG_TOOLS_TMEEHO84 #define WLOG_TOOLS_TMEEHO84 #include "bs_kernel.h" #include "conf.h" #include <limits> // DEBUG //#include <iostream> namespace blue_sky { // hidden implementation namespace { typedef v_float::iterator vf_iterator; typedef v_float::const_iterator cvf_iterator; typedef v_float::reverse_iterator vf_riterator; typedef v_float::const_reverse_iterator cvf_riterator; // depth and share same iterator type template< class data_iterator, class grid_iterator, class res_iterator > void projection_impl( //const spv_float& wlog_data, const spv_float& wlog_dept, const data_iterator& p_data_begin, const data_iterator& p_data_end, const data_iterator& p_dept_begin, const data_iterator& p_dept_end, grid_iterator& p_grid, const grid_iterator& p_grid_end, res_iterator& p_res ) { // calc wlog size const ulong wlog_sz = std::min< ulong >(p_data_end - p_data_begin, p_dept_end - p_dept_begin); if(wlog_sz == 0) return; // find starting point on well log data_iterator p_dept = std::lower_bound( p_dept_begin, p_dept_end, *p_grid ); if(p_dept == p_dept_end) // grid is fully outside of well log depths return; // setup iterators data_iterator p_data = p_data_begin + (p_dept - p_dept_begin); const res_iterator p_res_end = p_res + (p_grid_end - p_grid - 1); // position dest grid to next boundary ++p_grid; // main cycle t_float win_sum = 0; // win_sz counts only valid numbers that fits in window // raw_sz counts all values in window, including NaNs ulong win_sz = 0, raw_sz = 0; while(p_grid != p_grid_end) { // if we reached window boundary if(*p_dept > *p_grid) { if(win_sz) *p_res = win_sum / win_sz; else if(!raw_sz && (p_dept != p_dept_begin)) { // assign prev log value only if we had no NaNs in window *p_res = *(p_data - 1); } // next step on dest grid and resulting array if(++p_res == p_res_end) break; ++p_grid; win_sum = 0; win_sz = 0; raw_sz = 0; } else { // we're inside window // check for NaN if(!(*p_data != *p_data)) { win_sum += *p_data; ++win_sz; } // count all values in raw_sz ++raw_sz; // next step in well log ++p_data; ++p_dept; if(p_dept == p_dept_end) { if(win_sz) *p_res = win_sum / win_sz; break; } } } } } // eof hidden namespace BS_API_PLUGIN spv_float wlog_mean_projection( spv_float wlog_data, spv_float wlog_dept, spv_float dest_grid ) { // sanity spv_float res = BS_KERNEL.create_object(v_float::bs_type()); if(!wlog_data->size() || !wlog_dept->size() || dest_grid->size() < 2 || !res) return res; res->resize(dest_grid->size() - 1); // fill resulting array with NaN std::fill(res->begin(), res->end(), std::numeric_limits< double >::quiet_NaN()); // check grid ordering if(dest_grid->ss(0) < dest_grid->ss(dest_grid->size() - 1)) { // normal ordering cvf_iterator p_grid = dest_grid->begin(); const cvf_iterator p_grid_end = dest_grid->end(); vf_iterator p_res = res->begin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } } else { // reversed grid ordering cvf_riterator p_grid = dest_grid->rbegin(); const cvf_riterator p_grid_end = dest_grid->rend(); vf_riterator p_res = res->rbegin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } //projection_impl(wlog_data, wlog_dept, p_grid, p_grid_end, p_res); } return res; } } /* namespace blue_sky */ #endif /* end of include guard: WLOG_TOOLS_TMEEHO84 */ <|endoftext|>
<commit_before>/* * Distributed under the MIT License (See accompanying file /LICENSE ) */ #include "logger.hpp" #include <memory> #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_sinks.h> #include <spdlog/sinks/dist_sink.h> #include <spdlog/fmt/ostr.h> #ifdef _WIN32 #include <spdlog/sinks/wincolor_sink.h> #if defined (_DEBUG) && defined(_MSC_VER) #include <spdlog/sinks/msvc_sink.h> #endif // _DEBUG && _MSC_VER #else #include <spdlog/sinks/ansicolor_sink.h> #endif namespace ModernCppCI { Logger::Logger(const string& section) { section_ = section; } auto create_spdlog() { #ifdef _WIN32 auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>(); #else auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>(); #endif auto dist_sink = make_shared<spdlog::sinks::dist_sink_st>(); dist_sink->add_sink(color_sink); #if defined (_DEBUG) && defined(_MSC_VER) auto debug_sink = make_shared<spdlog::sinks::msvc_sink_st>(); dist_sink->add_sink(debug_sink); #endif // _DEBUG && _MSC_VER return spdlog::details::registry::instance().create("console", dist_sink); } std::shared_ptr<spdlog::logger> Logger::spdlog() { auto logger = spdlog::get("console"); if (logger == nullptr) { logger = create_spdlog(); } return logger; } } <commit_msg>remove unused imports<commit_after>/* * Distributed under the MIT License (See accompanying file /LICENSE ) */ #include "logger.hpp" #include <spdlog/sinks/dist_sink.h> #ifdef _WIN32 #include <spdlog/sinks/wincolor_sink.h> #if defined (_DEBUG) && defined(_MSC_VER) #include <spdlog/sinks/msvc_sink.h> #endif // _DEBUG && _MSC_VER #else #include <spdlog/sinks/ansicolor_sink.h> #endif namespace ModernCppCI { Logger::Logger(const string& section) { section_ = section; } auto create_spdlog() { #ifdef _WIN32 auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>(); #else auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>(); #endif auto dist_sink = make_shared<spdlog::sinks::dist_sink_st>(); dist_sink->add_sink(color_sink); #if defined (_DEBUG) && defined(_MSC_VER) auto debug_sink = make_shared<spdlog::sinks::msvc_sink_st>(); dist_sink->add_sink(debug_sink); #endif // _DEBUG && _MSC_VER return spdlog::details::registry::instance().create("console", dist_sink); } std::shared_ptr<spdlog::logger> Logger::spdlog() { auto logger = spdlog::get("console"); if (logger == nullptr) { logger = create_spdlog(); } return logger; } } <|endoftext|>
<commit_before>#include "PhysicsService.hpp" namespace Core { PhysicsService::PhysicsService(): m_objectList() {}; PObject* PhysicsService::CreateObject(const PShape* p_shape) { m_objectList.push_back(new Core::PObject(p_shape)); list<PObject*>::iterator it = m_objectList.end(); it--; (*it)->m_iterator = it; return *it; } void PhysicsService::DestroyObject(PObject* p_object) { list<PObject*>::iterator it = p_object->m_iterator; delete (*it); m_objectList.erase(it); } void PhysicsService::Step(float delta_time) { //update state for(list<PObject*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { (*it)->Advance(delta_time); } //detect collisions for(list<PObject*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { list<PObject*>::iterator it2 = it; for(it2++; it2 != m_objectList.end(); it2++) { if(CollideObjects(*(*it), *(*it2))) { callback(*(*it), *(*it2)); } } } } } <commit_msg>Added callback pointer init and NULL check<commit_after>#include "PhysicsService.hpp" namespace Core { PhysicsService::PhysicsService(): m_objectList() { callback = NULL; }; PObject* PhysicsService::CreateObject(const PShape* p_shape) { m_objectList.push_back(new Core::PObject(p_shape)); list<PObject*>::iterator it = m_objectList.end(); it--; (*it)->m_iterator = it; return *it; } void PhysicsService::DestroyObject(PObject* p_object) { list<PObject*>::iterator it = p_object->m_iterator; delete (*it); m_objectList.erase(it); } void PhysicsService::Step(float delta_time) { //update state for(list<PObject*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { (*it)->Advance(delta_time); } //detect collisions for(list<PObject*>::iterator it = m_objectList.begin(); it != m_objectList.end(); it++) { list<PObject*>::iterator it2 = it; for(it2++; it2 != m_objectList.end(); it2++) { if(CollideObjects(*(*it), *(*it2))) { if(callback != NULL) callback(*(*it), *(*it2)); } } } } } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 2019-3-30 21:04:45 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, Q; string S; string T = ""; string D = ""; int f(int n) { for (auto i = 0; i < Q; i++) { if (S[n] == T[i]) { if (D[i] == 'L') { n--; } else { n++; } } if (!(0 <= n && n < N)) { return n; } } return n; } int main() { cin >> N >> Q >> S; for (auto i = 0; i < N; i++) { string t, d; cin >> t >> d; T = T + t; D = D + d; } #if DEBUG == 1 cerr << "T = " << T << endl; cerr << "D = " << D << endl; #endif int ok = N; int ng = -1; while (abs(ok - ng) > 1) { int t = (ok + ng) / 2; if (f(t) == -1) { ng = t; } else { ok = t; } } int left = ok; ok = -1; ng = N; while (abs(ok - ng) > 1) { int t = (ok + ng) / 2; if (f(t) == N) { ng = t; } else { ok = t; } } int right = ok; #if DEBUG == 1 cerr << "left = " << left << ", right = " << right << endl; cerr << "f(" << left << ") = " << f(left) << endl; cerr << "f(" << right << ") = " << f(right) << endl; #endif cout << right - left + 1 << endl; }<commit_msg>submit C.cpp to 'C - Snuke the Wizard' (exawizards2019) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : C.cpp * Author : Kazune Takahashi * Created : 2019-3-30 21:04:45 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, Q; string S; string T = ""; string D = ""; int f(int n) { for (auto i = 0; i < Q; i++) { if (S[n] == T[i]) { if (D[i] == 'L') { n--; } else { n++; } } if (!(0 <= n && n < N)) { return n; } } return n; } int main() { cin >> N >> Q >> S; for (auto i = 0; i < Q; i++) { string t, d; cin >> t >> d; T = T + t; D = D + d; } #if DEBUG == 1 cerr << "T = " << T << endl; cerr << "D = " << D << endl; #endif int ok = N; int ng = -1; while (abs(ok - ng) > 1) { int t = (ok + ng) / 2; if (f(t) == -1) { ng = t; } else { ok = t; } } int left = ok; ok = -1; ng = N; while (abs(ok - ng) > 1) { int t = (ok + ng) / 2; if (f(t) == N) { ng = t; } else { ok = t; } } int right = ok; #if DEBUG == 1 cerr << "left = " << left << ", right = " << right << endl; cerr << "f(" << left << ") = " << f(left) << endl; cerr << "f(" << right << ") = " << f(right) << endl; #endif cout << right - left + 1 << endl; }<|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include <TChain.h> #include <TFile.h> #include <TList.h> #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliESD.h" #include "AliAODEvent.h" #include "AliAODHeader.h" #include "AliVEvent.h" #include "AliAODHandler.h" #include "AliAODInputHandler.h" #include "AliMCEventHandler.h" #include "AliInputEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliLog.h" ClassImp(AliAnalysisTaskSE) //////////////////////////////////////////////////////////////////////// Bool_t AliAnalysisTaskSE::fgHeaderCopied = kFALSE; AliAODHeader* AliAnalysisTaskSE::fgAODHeader = NULL; AliAnalysisTaskSE::AliAnalysisTaskSE(): AliAnalysisTask(), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Default constructor } AliAnalysisTaskSE::AliAnalysisTaskSE(const char* name): AliAnalysisTask(name, "AnalysisTaskSE"), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Default constructor DefineInput (0, TChain::Class()); DefineOutput(0, TTree::Class()); } AliAnalysisTaskSE::AliAnalysisTaskSE(const AliAnalysisTaskSE& obj): AliAnalysisTask(obj), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Copy constructor fDebug = obj.fDebug; fEntry = obj.fEntry; fInputEvent = obj.fInputEvent; fInputHandler = obj.fInputHandler; fOutputAOD = obj.fOutputAOD; fMCEvent = obj.fMCEvent; fTreeA = obj.fTreeA; printf("Constructor (3) \n"); } AliAnalysisTaskSE& AliAnalysisTaskSE::operator=(const AliAnalysisTaskSE& other) { // Assignment AliAnalysisTask::operator=(other); fDebug = other.fDebug; fEntry = other.fEntry; fInputEvent = other.fInputEvent; fInputHandler = other.fInputHandler; fOutputAOD = other.fOutputAOD; fMCEvent = other.fMCEvent; fTreeA = other.fTreeA; return *this; } void AliAnalysisTaskSE::ConnectInputData(Option_t* /*option*/) { // Connect the input data if (fDebug > 1) printf("AnalysisTaskSE::ConnectInputData() \n"); // // ESD // fInputHandler = (AliInputEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler()); // // Monte Carlo // AliMCEventHandler* mcH = 0; mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); if (mcH) fMCEvent = mcH->MCEvent(); if (fInputHandler) { fInputEvent = fInputHandler->GetEvent(); } else if( fMCEvent ) { AliWarning("No Input Event Handler connected, only MC Truth Event Handler") ; } else { AliError("No Input Event Handler connected") ; return ; } } void AliAnalysisTaskSE::CreateOutputObjects() { // Create the output container // // Default AOD if (fDebug > 1) printf("AnalysisTaskSE::CreateOutPutData() \n"); AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (handler) { fOutputAOD = handler->GetAOD(); fTreeA = handler->GetTree(); // Check if AOD Header replication has been required if (!(handler->IsStandard()) && (handler->NeedsHeaderReplication()) && !(fgAODHeader)) { fgAODHeader = new AliAODHeader; handler->AddBranch("AliAODHeader", &fgAODHeader); } } else { AliWarning("No AOD Event Handler connected.") ; } UserCreateOutputObjects(); } void AliAnalysisTaskSE::Exec(Option_t* option) { // // Exec analysis of one event if (fDebug > 1) AliInfo("AliAnalysisTaskSE::Exec() \n"); if( fInputHandler ) fEntry = fInputHandler->GetReadEntry(); else if( fMCEvent ) fEntry = fMCEvent->Header()->GetEvent(); if ( !((Entry()-1)%100) && fDebug > 0) AliInfo(Form("%s ----> Processing event # %lld", CurrentFileName(), Entry())); AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (!(handler->IsStandard()) && (handler->NeedsHeaderReplication()) && (fgAODHeader)) { // Header should be replicated AliAODInputHandler* aodH = dynamic_cast<AliAODInputHandler*>(fInputHandler); if (aodH) { // Input is AOD fgAODHeader = dynamic_cast<AliAODHeader*>(InputEvent()->GetHeader()); fgHeaderCopied = kTRUE; } } // Call the user analysis UserExec(option); PostData(0, fTreeA); } const char* AliAnalysisTaskSE::CurrentFileName() { // Returns the current file name if( fInputHandler ) return fInputHandler->GetTree()->GetCurrentFile()->GetName(); else if( fMCEvent ) return ((AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()))->TreeK()->GetCurrentFile()->GetName(); else return ""; } void AliAnalysisTaskSE::AddAODBranch(const char* cname, void* addobj) { // Add a new branch to the aod tree AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (handler) { handler->AddBranch(cname, addobj); } } <commit_msg>Protection in case there is no output handler.<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ #include <TROOT.h> #include <TSystem.h> #include <TInterpreter.h> #include <TChain.h> #include <TFile.h> #include <TList.h> #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliESD.h" #include "AliAODEvent.h" #include "AliAODHeader.h" #include "AliVEvent.h" #include "AliAODHandler.h" #include "AliAODInputHandler.h" #include "AliMCEventHandler.h" #include "AliInputEventHandler.h" #include "AliMCEvent.h" #include "AliStack.h" #include "AliLog.h" ClassImp(AliAnalysisTaskSE) //////////////////////////////////////////////////////////////////////// Bool_t AliAnalysisTaskSE::fgHeaderCopied = kFALSE; AliAODHeader* AliAnalysisTaskSE::fgAODHeader = NULL; AliAnalysisTaskSE::AliAnalysisTaskSE(): AliAnalysisTask(), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Default constructor } AliAnalysisTaskSE::AliAnalysisTaskSE(const char* name): AliAnalysisTask(name, "AnalysisTaskSE"), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Default constructor DefineInput (0, TChain::Class()); DefineOutput(0, TTree::Class()); } AliAnalysisTaskSE::AliAnalysisTaskSE(const AliAnalysisTaskSE& obj): AliAnalysisTask(obj), fDebug(0), fEntry(0), fInputEvent(0x0), fInputHandler(0x0), fOutputAOD(0x0), fMCEvent(0x0), fTreeA(0x0) { // Copy constructor fDebug = obj.fDebug; fEntry = obj.fEntry; fInputEvent = obj.fInputEvent; fInputHandler = obj.fInputHandler; fOutputAOD = obj.fOutputAOD; fMCEvent = obj.fMCEvent; fTreeA = obj.fTreeA; printf("Constructor (3) \n"); } AliAnalysisTaskSE& AliAnalysisTaskSE::operator=(const AliAnalysisTaskSE& other) { // Assignment AliAnalysisTask::operator=(other); fDebug = other.fDebug; fEntry = other.fEntry; fInputEvent = other.fInputEvent; fInputHandler = other.fInputHandler; fOutputAOD = other.fOutputAOD; fMCEvent = other.fMCEvent; fTreeA = other.fTreeA; return *this; } void AliAnalysisTaskSE::ConnectInputData(Option_t* /*option*/) { // Connect the input data if (fDebug > 1) printf("AnalysisTaskSE::ConnectInputData() \n"); // // ESD // fInputHandler = (AliInputEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler()); // // Monte Carlo // AliMCEventHandler* mcH = 0; mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); if (mcH) fMCEvent = mcH->MCEvent(); if (fInputHandler) { fInputEvent = fInputHandler->GetEvent(); } else if( fMCEvent ) { AliWarning("No Input Event Handler connected, only MC Truth Event Handler") ; } else { AliError("No Input Event Handler connected") ; return ; } } void AliAnalysisTaskSE::CreateOutputObjects() { // Create the output container // // Default AOD if (fDebug > 1) printf("AnalysisTaskSE::CreateOutPutData() \n"); AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (handler) { fOutputAOD = handler->GetAOD(); fTreeA = handler->GetTree(); // Check if AOD Header replication has been required if (!(handler->IsStandard()) && (handler->NeedsHeaderReplication()) && !(fgAODHeader)) { fgAODHeader = new AliAODHeader; handler->AddBranch("AliAODHeader", &fgAODHeader); } } else { AliWarning("No AOD Event Handler connected.") ; } UserCreateOutputObjects(); } void AliAnalysisTaskSE::Exec(Option_t* option) { // // Exec analysis of one event if (fDebug > 1) AliInfo("AliAnalysisTaskSE::Exec() \n"); if( fInputHandler ) fEntry = fInputHandler->GetReadEntry(); else if( fMCEvent ) fEntry = fMCEvent->Header()->GetEvent(); if ( !((Entry()-1)%100) && fDebug > 0) AliInfo(Form("%s ----> Processing event # %lld", CurrentFileName(), Entry())); AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (handler) { if (!(handler->IsStandard()) && (handler->NeedsHeaderReplication()) && (fgAODHeader)) { // Header should be replicated AliAODInputHandler* aodH = dynamic_cast<AliAODInputHandler*>(fInputHandler); if (aodH) { // Input is AOD fgAODHeader = dynamic_cast<AliAODHeader*>(InputEvent()->GetHeader()); fgHeaderCopied = kTRUE; } } } // Call the user analysis UserExec(option); PostData(0, fTreeA); } const char* AliAnalysisTaskSE::CurrentFileName() { // Returns the current file name if( fInputHandler ) return fInputHandler->GetTree()->GetCurrentFile()->GetName(); else if( fMCEvent ) return ((AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()))->TreeK()->GetCurrentFile()->GetName(); else return ""; } void AliAnalysisTaskSE::AddAODBranch(const char* cname, void* addobj) { // Add a new branch to the aod tree AliAODHandler* handler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (handler) { handler->AddBranch(cname, addobj); } } <|endoftext|>
<commit_before>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 "applicationmodel.h" #include "domain/artifactqueries.h" #include "domain/noterepository.h" #include "domain/tagqueries.h" #include "domain/tagrepository.h" #include "domain/taskqueries.h" #include "domain/taskrepository.h" #include "presentation/artifacteditormodel.h" #include "presentation/availablepagesmodel.h" #include "presentation/availablesourcesmodel.h" #include "presentation/datasourcelistmodel.h" #include "utils/dependencymanager.h" using namespace Presentation; ApplicationModel::ApplicationModel(QObject *parent) : QObject(parent), m_availableSources(0), m_availablePages(0), m_currentPage(0), m_editor(0), m_artifactQueries(Utils::DependencyManager::globalInstance().create<Domain::ArtifactQueries>()), m_projectQueries(Utils::DependencyManager::globalInstance().create<Domain::ProjectQueries>()), m_projectRepository(Utils::DependencyManager::globalInstance().create<Domain::ProjectRepository>()), m_contextQueries(Utils::DependencyManager::globalInstance().create<Domain::ContextQueries>()), m_contextRepository(Utils::DependencyManager::globalInstance().create<Domain::ContextRepository>()), m_sourceQueries(Utils::DependencyManager::globalInstance().create<Domain::DataSourceQueries>()), m_sourceRepository(Utils::DependencyManager::globalInstance().create<Domain::DataSourceRepository>()), m_taskQueries(Utils::DependencyManager::globalInstance().create<Domain::TaskQueries>()), m_taskRepository(Utils::DependencyManager::globalInstance().create<Domain::TaskRepository>()), m_taskSourcesModel(0), m_noteRepository(Utils::DependencyManager::globalInstance().create<Domain::NoteRepository>()), m_noteSourcesModel(0), m_tagQueries(Utils::DependencyManager::globalInstance().create<Domain::TagQueries>()), m_tagRepository(0), m_ownInterface(true) { MetaTypes::registerAll(); } ApplicationModel::ApplicationModel(Domain::ArtifactQueries *artifactQueries, Domain::ProjectQueries *projectQueries, Domain::ProjectRepository *projectRepository, Domain::ContextQueries *contextQueries, Domain::ContextRepository *contextRepository, Domain::DataSourceQueries *sourceQueries, Domain::DataSourceRepository *sourceRepository, Domain::TaskQueries *taskQueries, Domain::TaskRepository *taskRepository, Domain::NoteRepository *noteRepository, Domain::TagQueries *tagQueries, Domain::TagRepository *tagRepository, QObject *parent) : QObject(parent), m_availableSources(0), m_availablePages(0), m_currentPage(0), m_editor(0), m_artifactQueries(artifactQueries), m_projectQueries(projectQueries), m_projectRepository(projectRepository), m_contextQueries(contextQueries), m_contextRepository(contextRepository), m_sourceQueries(sourceQueries), m_sourceRepository(sourceRepository), m_taskQueries(taskQueries), m_taskRepository(taskRepository), m_taskSourcesModel(0), m_noteRepository(noteRepository), m_noteSourcesModel(0), m_tagQueries(tagQueries), m_tagRepository(tagRepository), m_ownInterface(false) { MetaTypes::registerAll(); } ApplicationModel::~ApplicationModel() { if (m_ownInterface) { delete m_artifactQueries; delete m_sourceQueries; delete m_taskQueries; delete m_taskRepository; delete m_tagQueries; delete m_tagRepository; delete m_noteRepository; } } QAbstractItemModel *ApplicationModel::noteSourcesModel() { if (!m_noteSourcesModel) { m_noteSourcesModel = new DataSourceListModel([this] { return noteSources(); }, this); } return m_noteSourcesModel; } Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::noteSources() { if (!m_noteSources) { m_noteSources = m_sourceQueries->findNotes(); } return m_noteSources; } Domain::DataSource::Ptr ApplicationModel::defaultNoteDataSource() { QList<Domain::DataSource::Ptr> sources = noteSources()->data(); if (sources.isEmpty()) return Domain::DataSource::Ptr(); auto source = std::find_if(sources.begin(), sources.end(), [this] (const Domain::DataSource::Ptr &source) { return m_noteRepository->isDefaultSource(source); }); if (source != sources.end()) return *source; else return sources.first(); } QAbstractItemModel *ApplicationModel::taskSourcesModel() { if (!m_taskSourcesModel) { m_taskSourcesModel = new DataSourceListModel([this] { return taskSources(); }, this); } return m_taskSourcesModel; } Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::taskSources() { if (!m_taskSources) { m_taskSources = m_sourceQueries->findTasks(); } return m_taskSources; } Domain::DataSource::Ptr ApplicationModel::defaultTaskDataSource() { QList<Domain::DataSource::Ptr> sources = taskSources()->data(); if (sources.isEmpty()) return Domain::DataSource::Ptr(); auto source = std::find_if(sources.begin(), sources.end(), [this] (const Domain::DataSource::Ptr &source) { return m_taskRepository->isDefaultSource(source); }); if (source != sources.end()) return *source; else return sources.first(); } QObject *ApplicationModel::availableSources() { if (!m_availableSources) { m_availableSources = new AvailableSourcesModel(m_sourceQueries, m_sourceRepository, this); } return m_availableSources; } QObject *ApplicationModel::availablePages() { if (!m_availablePages) { m_availablePages = new AvailablePagesModel(m_artifactQueries, m_projectQueries, m_projectRepository, m_contextQueries, m_contextRepository, m_taskQueries, m_taskRepository, m_noteRepository, m_tagQueries, m_tagRepository, this); } return m_availablePages; } QObject *ApplicationModel::currentPage() { return m_currentPage; } QObject *ApplicationModel::editor() { if (!m_editor) { m_editor = new ArtifactEditorModel(m_taskRepository, m_noteRepository, this); } return m_editor; } void ApplicationModel::setCurrentPage(QObject *page) { if (page == m_currentPage) return; m_currentPage = page; emit currentPageChanged(page); } void ApplicationModel::setDefaultNoteDataSource(Domain::DataSource::Ptr source) { m_noteRepository->setDefaultSource(source); } void ApplicationModel::setDefaultTaskDataSource(Domain::DataSource::Ptr source) { m_taskRepository->setDefaultSource(source); } <commit_msg>Minor Fix : delete all pointers that we created in the first place<commit_after>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 "applicationmodel.h" #include "domain/artifactqueries.h" #include "domain/contextqueries.h" #include "domain/contextrepository.h" #include "domain/projectqueries.h" #include "domain/projectrepository.h" #include "domain/noterepository.h" #include "domain/tagqueries.h" #include "domain/tagrepository.h" #include "domain/taskqueries.h" #include "domain/taskrepository.h" #include "presentation/artifacteditormodel.h" #include "presentation/availablepagesmodel.h" #include "presentation/availablesourcesmodel.h" #include "presentation/datasourcelistmodel.h" #include "utils/dependencymanager.h" using namespace Presentation; ApplicationModel::ApplicationModel(QObject *parent) : QObject(parent), m_availableSources(0), m_availablePages(0), m_currentPage(0), m_editor(0), m_artifactQueries(Utils::DependencyManager::globalInstance().create<Domain::ArtifactQueries>()), m_projectQueries(Utils::DependencyManager::globalInstance().create<Domain::ProjectQueries>()), m_projectRepository(Utils::DependencyManager::globalInstance().create<Domain::ProjectRepository>()), m_contextQueries(Utils::DependencyManager::globalInstance().create<Domain::ContextQueries>()), m_contextRepository(Utils::DependencyManager::globalInstance().create<Domain::ContextRepository>()), m_sourceQueries(Utils::DependencyManager::globalInstance().create<Domain::DataSourceQueries>()), m_sourceRepository(Utils::DependencyManager::globalInstance().create<Domain::DataSourceRepository>()), m_taskQueries(Utils::DependencyManager::globalInstance().create<Domain::TaskQueries>()), m_taskRepository(Utils::DependencyManager::globalInstance().create<Domain::TaskRepository>()), m_taskSourcesModel(0), m_noteRepository(Utils::DependencyManager::globalInstance().create<Domain::NoteRepository>()), m_noteSourcesModel(0), m_tagQueries(Utils::DependencyManager::globalInstance().create<Domain::TagQueries>()), m_tagRepository(0), m_ownInterface(true) { MetaTypes::registerAll(); } ApplicationModel::ApplicationModel(Domain::ArtifactQueries *artifactQueries, Domain::ProjectQueries *projectQueries, Domain::ProjectRepository *projectRepository, Domain::ContextQueries *contextQueries, Domain::ContextRepository *contextRepository, Domain::DataSourceQueries *sourceQueries, Domain::DataSourceRepository *sourceRepository, Domain::TaskQueries *taskQueries, Domain::TaskRepository *taskRepository, Domain::NoteRepository *noteRepository, Domain::TagQueries *tagQueries, Domain::TagRepository *tagRepository, QObject *parent) : QObject(parent), m_availableSources(0), m_availablePages(0), m_currentPage(0), m_editor(0), m_artifactQueries(artifactQueries), m_projectQueries(projectQueries), m_projectRepository(projectRepository), m_contextQueries(contextQueries), m_contextRepository(contextRepository), m_sourceQueries(sourceQueries), m_sourceRepository(sourceRepository), m_taskQueries(taskQueries), m_taskRepository(taskRepository), m_taskSourcesModel(0), m_noteRepository(noteRepository), m_noteSourcesModel(0), m_tagQueries(tagQueries), m_tagRepository(tagRepository), m_ownInterface(false) { MetaTypes::registerAll(); } ApplicationModel::~ApplicationModel() { if (m_ownInterface) { delete m_artifactQueries; delete m_contextQueries; delete m_contextQueries; delete m_projectQueries; delete m_projectRepository; delete m_sourceQueries; delete m_taskQueries; delete m_taskRepository; delete m_tagQueries; delete m_tagRepository; delete m_noteRepository; } } QAbstractItemModel *ApplicationModel::noteSourcesModel() { if (!m_noteSourcesModel) { m_noteSourcesModel = new DataSourceListModel([this] { return noteSources(); }, this); } return m_noteSourcesModel; } Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::noteSources() { if (!m_noteSources) { m_noteSources = m_sourceQueries->findNotes(); } return m_noteSources; } Domain::DataSource::Ptr ApplicationModel::defaultNoteDataSource() { QList<Domain::DataSource::Ptr> sources = noteSources()->data(); if (sources.isEmpty()) return Domain::DataSource::Ptr(); auto source = std::find_if(sources.begin(), sources.end(), [this] (const Domain::DataSource::Ptr &source) { return m_noteRepository->isDefaultSource(source); }); if (source != sources.end()) return *source; else return sources.first(); } QAbstractItemModel *ApplicationModel::taskSourcesModel() { if (!m_taskSourcesModel) { m_taskSourcesModel = new DataSourceListModel([this] { return taskSources(); }, this); } return m_taskSourcesModel; } Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::taskSources() { if (!m_taskSources) { m_taskSources = m_sourceQueries->findTasks(); } return m_taskSources; } Domain::DataSource::Ptr ApplicationModel::defaultTaskDataSource() { QList<Domain::DataSource::Ptr> sources = taskSources()->data(); if (sources.isEmpty()) return Domain::DataSource::Ptr(); auto source = std::find_if(sources.begin(), sources.end(), [this] (const Domain::DataSource::Ptr &source) { return m_taskRepository->isDefaultSource(source); }); if (source != sources.end()) return *source; else return sources.first(); } QObject *ApplicationModel::availableSources() { if (!m_availableSources) { m_availableSources = new AvailableSourcesModel(m_sourceQueries, m_sourceRepository, this); } return m_availableSources; } QObject *ApplicationModel::availablePages() { if (!m_availablePages) { m_availablePages = new AvailablePagesModel(m_artifactQueries, m_projectQueries, m_projectRepository, m_contextQueries, m_contextRepository, m_taskQueries, m_taskRepository, m_noteRepository, m_tagQueries, m_tagRepository, this); } return m_availablePages; } QObject *ApplicationModel::currentPage() { return m_currentPage; } QObject *ApplicationModel::editor() { if (!m_editor) { m_editor = new ArtifactEditorModel(m_taskRepository, m_noteRepository, this); } return m_editor; } void ApplicationModel::setCurrentPage(QObject *page) { if (page == m_currentPage) return; m_currentPage = page; emit currentPageChanged(page); } void ApplicationModel::setDefaultNoteDataSource(Domain::DataSource::Ptr source) { m_noteRepository->setDefaultSource(source); } void ApplicationModel::setDefaultTaskDataSource(Domain::DataSource::Ptr source) { m_taskRepository->setDefaultSource(source); } <|endoftext|>
<commit_before>#ifndef DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_ #define DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_ #include <vector> #include <cassert> #include <unordered_set> #include <unordered_map> #include "random_variable.hpp" namespace dice { // Decomposition should treat given variable as always independent. class independent_tag{}; /** Decomposition should expect that given variable might appear in some * other variable. */ class dependent_tag{}; /** Object representing a decomposition of a function of random variables. * * Denote A a random variable. Let us assume that A depends on random * variables X1,..., Xn. Then, from Law of total probability: * P(A = k) = sum of * P(A = k | X1 = x1, ..., Xn = xn) * P(X1 = x1, ..., Xn = xn) * for all x1, ..., xn * Because events `X1 = x1, ..., Xn = xn` are disjoint and they form * the whole sample space (we are considering all such xi's) * * Purpose of this is that variables `A | X1 = x1, ..., Xn = xn` might * be independent. */ template<typename ValueType, typename ProbabilityType> class random_variable_decomposition { public: using var_type = random_variable<ValueType, ProbabilityType>; using value_type = ValueType; random_variable_decomposition() {} random_variable_decomposition(independent_tag, const var_type* variable) { assert(variable != nullptr); vars_.push_back(*variable); } random_variable_decomposition(independent_tag, const var_type& variable) { vars_.push_back(variable); } random_variable_decomposition(dependent_tag, const var_type* variable) { assert(variable != nullptr); deps_.push_back(variable); for (auto&& pair : variable->probability()) { vars_.emplace_back(constant_tag{}, pair.first); } } // Random variable constructors random_variable_decomposition( std::vector<std::pair<value_type, std::size_t>>&& list) : random_variable_decomposition(independent_tag{}, var_type(std::move(list))) { } random_variable_decomposition(bernoulli_tag, ProbabilityType success) : random_variable_decomposition(independent_tag{}, var_type(bernoulli_tag{}, success)) { } random_variable_decomposition(constant_tag, value_type value) : random_variable_decomposition(independent_tag{}, var_type(constant_tag{}, value)) { } // allow copy random_variable_decomposition( const random_variable_decomposition&) = default; random_variable_decomposition& operator=( const random_variable_decomposition&) = default; // allow move random_variable_decomposition( random_variable_decomposition&&) = default; random_variable_decomposition& operator=( random_variable_decomposition&&) = default; /** Compute sum of 2 random variables. * Random variables don't need to be indendent. * @param right hand side of the operator * @return distribution of the sum */ auto operator+(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a + value_b; }); } /** Subtract other random variable from this. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the subtraction */ auto operator-(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a - value_b; }); } /** Compute product of 2 random variables. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the product */ auto operator*(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a * value_b; }); } /** Divide this variable by other variable. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the division */ auto operator/(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a / value_b; }); } /** Multiply this random variable with -1. * @return negated random variable */ auto operator-() const { random_variable_decomposition result; result.deps_ = deps_; for (auto&& var : vars_) { result.vars_.push_back(-var); } return result; } /** Compute indicator: A < B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A < B * (i.e. a random variable with a bernoulli distribution) */ auto less_than(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a < b); }); } /** Compute indicator: A <= B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A <= B * (i.e. a random variable with a bernoulli distribution) */ auto less_than_or_equal( const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a <= b); }); } /** Compute indicator: A = B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A = B * (i.e. a random variable with a bernoulli distribution) */ auto equal(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a == b); }); } /** Compute indicator: A != B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable Y * @return indicator of A != B * (i.e. a random variable with a bernoulli distribution) */ auto not_equal(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a != b); }); } /** Compute indicator: A > B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A > B * (i.e. a random variable with a bernoulli distribution) */ auto greater_than(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a > b); }); } /** Compute indicator: A >= B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable Y * @return indicator of A >= YB * (i.e. a random variable with a bernoulli distribution) */ auto greater_than_or_equal( const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a >= b); }); } /** Compute indicator: A in [a, b] (where X is this random variable). * The interval is closed. * @param lower bound of the interval (a) * @param upper bound of the interval (b) * @return indicator of A in [a, b] * (i.e. a random variable with a bernoulli distribution) */ template<typename T> auto in(T&& lower_bound, T&& upper_bound) const { random_variable_decomposition result; result.deps_ = deps_; for (auto&& var : vars_) { result.vars_.push_back(var.in(lower_bound, upper_bound)); } return result; } /** Roll num_rolls times with a dice of num_sides. * Random variables have to be independent. * @param number of rolls * @param number of dice sides * @return distribution of the dice roll */ friend auto roll( const random_variable_decomposition& num_rolls, const random_variable_decomposition& num_sides) { if (num_rolls.vars_.size() > 1 || num_sides.vars_.size() > 1) throw std::runtime_error( "Variable names are not supported in roll operator"); auto var = roll(num_rolls.vars_.front(), num_sides.vars_.front()); return random_variable_decomposition(independent_tag{}, &var); } /** Compute expected value of this random variable. * @return expected value of this variable */ auto expected_value() { return rand_var().expected_value(); } /** Compute variance of this random variable. * @return variance of this variable */ auto variance() { return rand_var().variance(); } /** Compute function of 2 random variables: A and B. * Variables does not need to be independent. * @param other random variable B * @param combination function * @return random variable that is a function of A and B */ template<typename CombinationFunc> auto combine( const random_variable_decomposition& other, CombinationFunc combination) const { random_variable_decomposition result; // compute union of the deps_ sets sorted_union(deps_, other.deps_, result.deps_); // compute number of values for the deps_ vector std::size_t num_values = 1; for (auto&& var : result.deps_) { num_values *= var->probability().size(); } std::unordered_set<const var_type*> in_a{ deps_.begin(), deps_.end() }; std::unordered_set<const var_type*> in_b{ other.deps_.begin(), other.deps_.end() }; // compute the conditional random variables for (std::size_t i = 0; i < num_values; ++i) { std::size_t index_a = 0; std::size_t index_b = 0; std::size_t hash = i; std::size_t size_a = 1; std::size_t size_b = 1; for (auto&& var : result.deps_) { if (in_a.find(var) != in_a.end()) { index_a += (hash % var->probability().size()) * size_a; size_a *= var->probability().size(); } if (in_b.find(var) != in_b.end()) { index_b += (hash % var->probability().size()) * size_b; size_b *= var->probability().size(); } hash /= var->probability().size(); } result.vars_.push_back( vars_[index_a].combine(other.vars_[index_b], combination)); } return result; } /** Convert this decomposition to basic random variable. * Notice, by performing this operation, we lose information * about (in)dependence. * @return plain random variable */ var_type to_random_variable() const { var_type result; // if there are no dependent variables if (deps_.empty()) { assert(vars_.size() <= 1); if (vars_.size() == 1) return vars_[0]; return result; } // store variables distributions in an array so we can access ith // element faster std::vector< std::vector< std::pair<value_type, ProbabilityType>>> vars; for (auto&& var : deps_) { vars.push_back( std::vector<std::pair<value_type, ProbabilityType>>( var->probability().begin(), var->probability().end() )); } for (std::size_t i = 0; i < vars_.size(); ++i) { // compute P(X = x) ProbabilityType prob = 1; std::size_t hash = i; for (auto&& value : vars) { auto index = hash % value.size(); prob *= value[index].second; hash /= value.size(); } // compute P(A | X = x) * P(X = x) for (auto&& pair : vars_[i].probability()) { auto resp = result.probability_.insert(std::make_pair( pair.first, pair.second * prob )); if (!resp.second) { resp.first->second += pair.second * prob; } } } return result; } /** Map value -> probability of this random variable. * @return probability map */ auto probability() const { auto var = to_random_variable(); return var.probability(); } /** Return a reference to a basic random variable with the same * distribution. This object is converted in the first call. * Subsequent calls just retrieve the cached value. */ const var_type& rand_var() { if (dist_.probability_.empty()) { dist_ = to_random_variable(); } return dist_; } private: /** Resulting random variable. * This is cached value of the to_random_variable() call. */ var_type dist_; /** Set of variables on which this random variable depends. * It is kept sorted by the pointer value. This simplifies the * combination algorithm as we can make some assumptions in the * variable index computation. * * Note we store a pointer to each variable. Therefore, they have to * outlive this object. */ std::vector<const var_type*> deps_; /** List of conditional random variables. * * Each item on this list is a r.v.: `A | X = x` where X is a random * vector deps_ and x is a value of this random vector. * * `x` is defined implicitly by the index. For example, consider * variables deps_ = (X, Y) whose values are 1 or 2. Order of variables * in this list is as follows: * -# A | X = 1, Y = 1 * -# A | X = 2, Y = 1 * -# A | X = 1, Y = 2 * -# A | X = 2, Y = 2 */ std::vector<var_type> vars_; /** Compute union of sorted lists A and B. * Both lists have to be sorted by given comparer. * @param sorted list A * @param sorted list B * @param list where the sorted union will be stored * @param comparer */ template<typename T, typename Less = std::less<T>> static void sorted_union( const std::vector<T>& a, const std::vector<T>& b, std::vector<T>& result, Less is_less = Less()) { auto left = a.begin(); auto right = b.begin(); for (;;) { if (left == a.end() && right == b.end()) { break; } else if (right == b.end()) { result.push_back(*left++); } else if (left == a.end()) { result.push_back(*right++); } else if (is_less(*left, *right)) { result.push_back(*left++); } else if (is_less(*right, *left)) { result.push_back(*right++); } else // *left == *right { result.push_back(*left); ++left; ++right; } } } }; } #endif // DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_<commit_msg>Refactor sorted_union: use return value<commit_after>#ifndef DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_ #define DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_ #include <vector> #include <cassert> #include <unordered_set> #include <unordered_map> #include "random_variable.hpp" namespace dice { // Decomposition should treat given variable as always independent. class independent_tag{}; /** Decomposition should expect that given variable might appear in some * other variable. */ class dependent_tag{}; /** Object representing a decomposition of a function of random variables. * * Denote A a random variable. Let us assume that A depends on random * variables X1,..., Xn. Then, from Law of total probability: * P(A = k) = sum of * P(A = k | X1 = x1, ..., Xn = xn) * P(X1 = x1, ..., Xn = xn) * for all x1, ..., xn * Because events `X1 = x1, ..., Xn = xn` are disjoint and they form * the whole sample space (we are considering all such xi's) * * Purpose of this is that variables `A | X1 = x1, ..., Xn = xn` might * be independent. */ template<typename ValueType, typename ProbabilityType> class random_variable_decomposition { public: using var_type = random_variable<ValueType, ProbabilityType>; using value_type = ValueType; random_variable_decomposition() {} random_variable_decomposition(independent_tag, const var_type* variable) { assert(variable != nullptr); vars_.push_back(*variable); } random_variable_decomposition(independent_tag, const var_type& variable) { vars_.push_back(variable); } random_variable_decomposition(dependent_tag, const var_type* variable) { assert(variable != nullptr); deps_.push_back(variable); for (auto&& pair : variable->probability()) { vars_.emplace_back(constant_tag{}, pair.first); } } // Random variable constructors random_variable_decomposition( std::vector<std::pair<value_type, std::size_t>>&& list) : random_variable_decomposition(independent_tag{}, var_type(std::move(list))) { } random_variable_decomposition(bernoulli_tag, ProbabilityType success) : random_variable_decomposition(independent_tag{}, var_type(bernoulli_tag{}, success)) { } random_variable_decomposition(constant_tag, value_type value) : random_variable_decomposition(independent_tag{}, var_type(constant_tag{}, value)) { } // allow copy random_variable_decomposition( const random_variable_decomposition&) = default; random_variable_decomposition& operator=( const random_variable_decomposition&) = default; // allow move random_variable_decomposition( random_variable_decomposition&&) = default; random_variable_decomposition& operator=( random_variable_decomposition&&) = default; /** Compute sum of 2 random variables. * Random variables don't need to be indendent. * @param right hand side of the operator * @return distribution of the sum */ auto operator+(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a + value_b; }); } /** Subtract other random variable from this. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the subtraction */ auto operator-(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a - value_b; }); } /** Compute product of 2 random variables. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the product */ auto operator*(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a * value_b; }); } /** Divide this variable by other variable. * Random variables don't need to be indendent. * @param right hand side of the operator * @return result of the division */ auto operator/(const random_variable_decomposition& other) const { return combine(other, [](auto&& value_a, auto&& value_b) { return value_a / value_b; }); } /** Multiply this random variable with -1. * @return negated random variable */ auto operator-() const { random_variable_decomposition result; result.deps_ = deps_; for (auto&& var : vars_) { result.vars_.push_back(-var); } return result; } /** Compute indicator: A < B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A < B * (i.e. a random variable with a bernoulli distribution) */ auto less_than(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a < b); }); } /** Compute indicator: A <= B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A <= B * (i.e. a random variable with a bernoulli distribution) */ auto less_than_or_equal( const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a <= b); }); } /** Compute indicator: A = B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A = B * (i.e. a random variable with a bernoulli distribution) */ auto equal(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a == b); }); } /** Compute indicator: A != B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable Y * @return indicator of A != B * (i.e. a random variable with a bernoulli distribution) */ auto not_equal(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a != b); }); } /** Compute indicator: A > B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable B * @return indicator of A > B * (i.e. a random variable with a bernoulli distribution) */ auto greater_than(const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a > b); }); } /** Compute indicator: A >= B (where A is this random variale). * Variables does not need to be indepedent. * @param other random variable Y * @return indicator of A >= YB * (i.e. a random variable with a bernoulli distribution) */ auto greater_than_or_equal( const random_variable_decomposition& other) const { return combine(other, [](auto&& a, auto&& b) { return static_cast<value_type>(a >= b); }); } /** Compute indicator: A in [a, b] (where A is this random variable). * The interval is closed. * @param lower bound of the interval (a) * @param upper bound of the interval (b) * @return indicator of A in [a, b] * (i.e. a random variable with a bernoulli distribution) */ template<typename T> auto in(T&& lower_bound, T&& upper_bound) const { random_variable_decomposition result; result.deps_ = deps_; for (auto&& var : vars_) { result.vars_.push_back(var.in(lower_bound, upper_bound)); } return result; } /** Roll num_rolls times with a dice of num_sides. * Random variables have to be independent. * @param number of rolls * @param number of dice sides * @return distribution of the dice roll */ friend auto roll( const random_variable_decomposition& num_rolls, const random_variable_decomposition& num_sides) { if (num_rolls.vars_.size() > 1 || num_sides.vars_.size() > 1) throw std::runtime_error( "Variable names are not supported in roll operator"); auto var = roll(num_rolls.vars_.front(), num_sides.vars_.front()); return random_variable_decomposition(independent_tag{}, &var); } /** Compute expected value of this random variable. * @return expected value of this variable */ auto expected_value() { return rand_var().expected_value(); } /** Compute variance of this random variable. * @return variance of this variable */ auto variance() { return rand_var().variance(); } /** Compute function of 2 random variables: A and B. * Variables does not need to be independent. * @param other random variable B * @param combination function * @return random variable that is a function of A and B */ template<typename CombinationFunc> auto combine( const random_variable_decomposition& other, CombinationFunc combination) const { random_variable_decomposition result; // compute union of the deps_ sets result.deps_ = sorted_union(deps_, other.deps_); // compute number of values for the deps_ vector std::size_t num_values = 1; for (auto&& var : result.deps_) { num_values *= var->probability().size(); } std::unordered_set<const var_type*> in_a{ deps_.begin(), deps_.end() }; std::unordered_set<const var_type*> in_b{ other.deps_.begin(), other.deps_.end() }; // compute the conditional random variables for (std::size_t i = 0; i < num_values; ++i) { std::size_t index_a = 0; std::size_t index_b = 0; std::size_t hash = i; std::size_t size_a = 1; std::size_t size_b = 1; for (auto&& var : result.deps_) { if (in_a.find(var) != in_a.end()) { index_a += (hash % var->probability().size()) * size_a; size_a *= var->probability().size(); } if (in_b.find(var) != in_b.end()) { index_b += (hash % var->probability().size()) * size_b; size_b *= var->probability().size(); } hash /= var->probability().size(); } result.vars_.push_back( vars_[index_a].combine(other.vars_[index_b], combination)); } return result; } /** Convert this decomposition to basic random variable. * Notice, by performing this operation, we lose information * about (in)dependence. * @return plain random variable */ var_type to_random_variable() const { var_type result; // if there are no dependent variables if (deps_.empty()) { assert(vars_.size() <= 1); if (vars_.size() == 1) return vars_[0]; return result; } // store variables distributions in an array so we can access ith // element faster std::vector< std::vector< std::pair<value_type, ProbabilityType>>> vars; for (auto&& var : deps_) { vars.push_back( std::vector<std::pair<value_type, ProbabilityType>>( var->probability().begin(), var->probability().end() )); } for (std::size_t i = 0; i < vars_.size(); ++i) { // compute P(X = x) ProbabilityType prob = 1; std::size_t hash = i; for (auto&& value : vars) { auto index = hash % value.size(); prob *= value[index].second; hash /= value.size(); } // compute P(A | X = x) * P(X = x) for (auto&& pair : vars_[i].probability()) { auto resp = result.probability_.insert(std::make_pair( pair.first, pair.second * prob )); if (!resp.second) { resp.first->second += pair.second * prob; } } } return result; } /** Map value -> probability of this random variable. * @return probability map */ auto probability() const { auto var = to_random_variable(); return var.probability(); } /** Return a reference to a basic random variable with the same * distribution. This object is converted in the first call. * Subsequent calls just retrieve the cached value. */ const var_type& rand_var() { if (dist_.probability_.empty()) { dist_ = to_random_variable(); } return dist_; } private: /** Resulting random variable. * This is cached value of the to_random_variable() call. */ var_type dist_; /** Set of variables on which this random variable depends. * It is kept sorted by the pointer value. This simplifies the * combination algorithm as we can make some assumptions in the * variable index computation. * * Note we store a pointer to each variable. Therefore, they have to * outlive this object. */ std::vector<const var_type*> deps_; /** List of conditional random variables. * * Each item on this list is a r.v.: `A | X = x` where X is a random * vector deps_ and x is a value of this random vector. * * `x` is defined implicitly by the index. For example, consider * variables deps_ = (X, Y) whose values are 1 or 2. Order of variables * in this list is as follows: * -# A | X = 1, Y = 1 * -# A | X = 2, Y = 1 * -# A | X = 1, Y = 2 * -# A | X = 2, Y = 2 */ std::vector<var_type> vars_; /** Compute union of sorted lists A and B. * Both lists have to be sorted by given comparer. * @param sorted list A * @param sorted list B * @param comparer * @return sorted union of lists A and B */ template<typename T, typename Less = std::less<T>> static std::vector<T> sorted_union( const std::vector<T>& a, const std::vector<T>& b, Less is_less = Less()) { std::vector<T> result; auto left = a.begin(); auto right = b.begin(); for (;;) { if (left == a.end() && right == b.end()) { break; } else if (right == b.end()) { result.push_back(*left++); } else if (left == a.end()) { result.push_back(*right++); } else if (is_less(*left, *right)) { result.push_back(*left++); } else if (is_less(*right, *left)) { result.push_back(*right++); } else // *left == *right { result.push_back(*left); ++left; ++right; } } return result; } }; } #endif // DICE_RANDOM_VARIABLE_DECOMPOSITION_HPP_<|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_IMPL_CONT_TRANSACT_HIST_HPP #define REALM_IMPL_CONT_TRANSACT_HIST_HPP #include <cstdint> #include <memory> #include <realm/column_binary.hpp> #include <realm/version_id.hpp> namespace realm { class Group; namespace _impl { /// Read-only access to history of changesets as needed to enable continuous /// transactions. class History { public: using version_type = VersionID::version_type; /// May be called during a read transaction to gain early access to the /// history as it appears in a new snapshot that succeeds the one bound in /// the current read transaction. /// /// May also be called at other times as long as the caller owns a read lock /// (SharedGroup::grab_read_lock()) on the Realm for the specified file size /// and top ref, and the allocator is in a 'free space clean' state /// (SlabAlloc::is_free_space_clean()). /// /// This function may cause a remapping of the Realm file /// (SlabAlloc::remap()) if it needs to make the new snapshot fully visible /// in memory. /// /// Note that this method of gaining early access to the history in a new /// snaphot only gives read access. It does not allow for modifications of /// the history or any other part of the new snapshot. For modifications to /// be allowed, `Group::m_top` (the parent of the history) would first have /// to be updated to reflect the new snapshot, but at that time we are no /// longer in an 'early access' situation. /// /// This is not a problem from the point of view of this history interface, /// as it only contains methods for reading from the history, but some /// implementations will want to also provide for ways to modify the /// history, but in those cases, modifications must occur only after the /// Group accessor has been fully updated to reflect the new snapshot. virtual void update_early_from_top_ref(version_type new_version, size_t new_file_size, ref_type new_top_ref) = 0; virtual void update_from_parent(version_type current_version) = 0; /// Get all changesets between the specified versions. References to those /// changesets will be made availble in successive entries of `buffer`. The /// number of retreived changesets is exactly `end_version - /// begin_version`. If this number is greater than zero, the changeset made /// avaialable in `buffer[0]` is the one that brought the database from /// `begin_version` to `begin_version + 1`. /// /// It is an error to specify a version (for \a begin_version or \a /// end_version) that is outside the range [V,W] where V is the version that /// immediately precedes the first changeset available in the history as the /// history appears in the **latest** available snapshot, and W is the /// versionm that immediately succeeds the last changeset available in the /// history as the history appears in the snapshot bound to the **current** /// transaction. This restriction is necessary to allow for different kinds /// of implementations of the history (separate standalone history or /// history as part of versioned Realm state). /// /// The calee retains ownership of the memory referenced by those entries, /// i.e., the memory referenced by `buffer[i].changeset` is **not** handed /// over to the caller. /// /// This function may be called only during a transaction (prior to /// initiation of commit operation), and only after a successfull invocation /// of update_early_from_top_ref(). In that case, the caller may assume that /// the memory references stay valid for the remainder of the transaction /// (up until initiation of the commit operation). virtual void get_changesets(version_type begin_version, version_type end_version, BinaryIterator* buffer) const noexcept = 0; /// \brief Specify the version of the oldest bound snapshot. /// /// This function must be called by the associated SharedGroup object during /// each successfully committed write transaction. It must be called before /// the transaction is finalized (Replication::finalize_commit()) or aborted /// (Replication::abort_transact()), but after the initiation of the commit /// operation (Replication::prepare_commit()). This allows history /// implementations to add new history entries before triming off old ones, /// and this, in turn, guarantees that the history never becomes empty, /// except in the initial empty Realm state. /// /// The caller must pass the version (\a version) of the oldest snapshot /// that is currently (or was recently) bound via a transaction of the /// current session. This gives the history implementation an opportunity to /// trim off leading (early) history entries. /// /// Since this function must be called during a write transaction, there /// will always be at least one snapshot that is currently bound via a /// transaction. /// /// The caller must guarantee that the passed version (\a version) is less /// than or equal to `begin_version` in all future invocations of /// get_changesets(). /// /// The caller is allowed to pass a version that is less than the version /// passed in a preceeding invocation. /// /// This function should be called as late as possible, to maximize the /// trimming opportunity, but at a time where the write transaction is still /// open for additional modifications. This is necessary because some types /// of histories are stored inside the Realm file. virtual void set_oldest_bound_version(version_type version) = 0; /// Get the list of uncommited changes accumulated so far in the current /// write transaction. /// /// The callee retains ownership of the referenced memory. The ownership is /// not handed over the the caller. /// /// This function may be called only during a write transaction (prior to /// initiation of commit operation). In that case, the caller may assume that the /// returned memory reference stays valid for the remainder of the transaction (up /// until initiation of the commit operation). virtual BinaryData get_uncommitted_changes() noexcept = 0; virtual void verify() const = 0; virtual ~History() noexcept { } }; } // namespace _impl } // namespace realm #endif // REALM_IMPL_CONTINUOUS_TRANSACTIONS_HISTORY_HPP <commit_msg>Typos in comments<commit_after>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_IMPL_CONT_TRANSACT_HIST_HPP #define REALM_IMPL_CONT_TRANSACT_HIST_HPP #include <cstdint> #include <memory> #include <realm/column_binary.hpp> #include <realm/version_id.hpp> namespace realm { class Group; namespace _impl { /// Read-only access to history of changesets as needed to enable continuous /// transactions. class History { public: using version_type = VersionID::version_type; /// May be called during a read transaction to gain early access to the /// history as it appears in a new snapshot that succeeds the one bound in /// the current read transaction. /// /// May also be called at other times as long as the caller owns a read lock /// (SharedGroup::grab_read_lock()) on the Realm for the specified file size /// and top ref, and the allocator is in a 'free space clean' state /// (SlabAlloc::is_free_space_clean()). /// /// This function may cause a remapping of the Realm file /// (SlabAlloc::remap()) if it needs to make the new snapshot fully visible /// in memory. /// /// Note that this method of gaining early access to the history in a new /// snapshot only gives read access. It does not allow for modifications of /// the history or any other part of the new snapshot. For modifications to /// be allowed, `Group::m_top` (the parent of the history) would first have /// to be updated to reflect the new snapshot, but at that time we are no /// longer in an 'early access' situation. /// /// This is not a problem from the point of view of this history interface, /// as it only contains methods for reading from the history, but some /// implementations will want to also provide for ways to modify the /// history, but in those cases, modifications must occur only after the /// Group accessor has been fully updated to reflect the new snapshot. virtual void update_early_from_top_ref(version_type new_version, size_t new_file_size, ref_type new_top_ref) = 0; virtual void update_from_parent(version_type current_version) = 0; /// Get all changesets between the specified versions. References to those /// changesets will be made available in successive entries of `buffer`. The /// number of retrieved changesets is exactly `end_version - /// begin_version`. If this number is greater than zero, the changeset made /// available in `buffer[0]` is the one that brought the database from /// `begin_version` to `begin_version + 1`. /// /// It is an error to specify a version (for \a begin_version or \a /// end_version) that is outside the range [V,W] where V is the version that /// immediately precedes the first changeset available in the history as the /// history appears in the **latest** available snapshot, and W is the /// version that immediately succeeds the last changeset available in the /// history as the history appears in the snapshot bound to the **current** /// transaction. This restriction is necessary to allow for different kinds /// of implementations of the history (separate standalone history or /// history as part of versioned Realm state). /// /// The callee retains ownership of the memory referenced by those entries, /// i.e., the memory referenced by `buffer[i].changeset` is **not** handed /// over to the caller. /// /// This function may be called only during a transaction (prior to /// initiation of commit operation), and only after a successful invocation /// of update_early_from_top_ref(). In that case, the caller may assume that /// the memory references stay valid for the remainder of the transaction /// (up until initiation of the commit operation). virtual void get_changesets(version_type begin_version, version_type end_version, BinaryIterator* buffer) const noexcept = 0; /// \brief Specify the version of the oldest bound snapshot. /// /// This function must be called by the associated SharedGroup object during /// each successfully committed write transaction. It must be called before /// the transaction is finalized (Replication::finalize_commit()) or aborted /// (Replication::abort_transact()), but after the initiation of the commit /// operation (Replication::prepare_commit()). This allows history /// implementations to add new history entries before trimming off old ones, /// and this, in turn, guarantees that the history never becomes empty, /// except in the initial empty Realm state. /// /// The caller must pass the version (\a version) of the oldest snapshot /// that is currently (or was recently) bound via a transaction of the /// current session. This gives the history implementation an opportunity to /// trim off leading (early) history entries. /// /// Since this function must be called during a write transaction, there /// will always be at least one snapshot that is currently bound via a /// transaction. /// /// The caller must guarantee that the passed version (\a version) is less /// than or equal to `begin_version` in all future invocations of /// get_changesets(). /// /// The caller is allowed to pass a version that is less than the version /// passed in a preceding invocation. /// /// This function should be called as late as possible, to maximize the /// trimming opportunity, but at a time where the write transaction is still /// open for additional modifications. This is necessary because some types /// of histories are stored inside the Realm file. virtual void set_oldest_bound_version(version_type version) = 0; /// Get the list of uncommitted changes accumulated so far in the current /// write transaction. /// /// The callee retains ownership of the referenced memory. The ownership is /// not handed over to the caller. /// /// This function may be called only during a write transaction (prior to /// initiation of commit operation). In that case, the caller may assume that the /// returned memory reference stays valid for the remainder of the transaction (up /// until initiation of the commit operation). virtual BinaryData get_uncommitted_changes() noexcept = 0; virtual void verify() const = 0; virtual ~History() noexcept { } }; } // namespace _impl } // namespace realm #endif // REALM_IMPL_CONTINUOUS_TRANSACTIONS_HISTORY_HPP <|endoftext|>
<commit_before>/** * ActionServer interface to the control_msgs/GripperCommand action * for a Robotiq S-Model device */ #include "robotiq_action_server/robotiq_s_model_action_server.h" // To keep the fully qualified names managable //Anonymous namespaces are file local -> sort of like global static objects namespace { using namespace robotiq_action_server; /* This struct is declared for the sole purpose of being used as an exception internally to keep the code clean (i.e. no output params). It is caught by the action_server and should not propogate outwards. If you use these functions yourself, beware. */ struct BadArgumentsError {}; GripperOutput goalToRegisterState(const GripperCommandGoal& goal, const SModelGripperParams& params) { GripperOutput result; result.rACT = 0x1; // active gripper result.rGTO = 0x1; // go to position result.rATR = 0x0; // No emergency release //result.rICS = 1; // individual control of scissor result.rSPA = 80; // finger speed; 80 for this specific case //result.rSPS = 255; // scissor speed if (goal.command.position > params.max_rad_ || goal.command.position < params.min_rad_) { ROS_WARN("Goal gripper rad size is out of range(%f to %f): %f m", params.min_rad_, params.max_rad_, goal.command.position); throw BadArgumentsError(); } if (goal.command.max_effort < params.min_effort_ || goal.command.max_effort > params.max_effort_) { ROS_WARN("Goal gripper effort out of range (%f to %f N): %f N", params.min_effort_, params.max_effort_, goal.command.max_effort); throw BadArgumentsError(); } //The register value for the closed pinch mode is 113, //the minimal register value for the finger is 6 , so wie divide with 107 double dist_per_tick = (params.max_rad_ - params.min_rad_) / 255; double eff_per_tick = (params.max_effort_ - params.min_effort_) / 255; result.rPRA = static_cast<uint8_t>((goal.command.position) / dist_per_tick); result.rFRA = static_cast<uint8_t>((goal.command.max_effort - params.min_effort_) / eff_per_tick); /* Register Value for scissor position: calculatet with the position of fingers (between 6 and 113) multiplied with max scissor position divided by max finger position. I'm not sure why it musst be 212 and 113 and noch 197 and 107, cause the scissor position starts with 15 and the finger position with 6. */ //result.rPRS = static_cast<uint8_t>(result.rPRA*(212.0/113.0)); ROS_INFO("Setting goal position register to %hhu", result.rPRA); ROS_INFO_STREAM("Goal command position: " << goal.command.position); ROS_INFO_STREAM("param min_rad: " << params.min_rad_); ROS_INFO_STREAM("param max_rad: " << params.max_rad_); ROS_INFO_STREAM(goal); return result; } /* This function is templatized because both GripperCommandResult and GripperCommandFeedback consist of the same fields yet have different types. Templates here act as a "duck typing" mechanism to avoid code duplication. */ template<typename T> T registerStateToResultT(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { T result; double dist_per_tick = (params.max_rad_ - params.min_rad_) / 255; double eff_per_tick = (params.max_effort_ - params.min_effort_) / 255; result.position = input.gPOA * dist_per_tick + params.min_rad_; result.effort = input.gCUA * eff_per_tick + params.min_effort_; result.stalled = input.gIMC == 0x1 || input.gIMC == 0x2; result.reached_goal = input.gPOA == goal_pos; return result; } // Inline api-transformers to avoid confusion when reading the action_server source inline GripperCommandResult registerStateToResult(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { return registerStateToResultT<GripperCommandResult>(input, params, goal_pos); } inline GripperCommandFeedback registerStateToFeedback(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { return registerStateToResultT<GripperCommandFeedback>(input, params, goal_pos); } } // end of anon namespace namespace robotiq_action_server { SModelGripperActionServer::SModelGripperActionServer(const std::string& name, const SModelGripperParams& params) : nh_() , as_(nh_, name, false) , action_name_(name) , gripper_params_(params) { as_.registerGoalCallback(boost::bind(&SModelGripperActionServer::goalCB, this)); as_.registerPreemptCallback(boost::bind(&SModelGripperActionServer::preemptCB, this)); state_sub_ = nh_.subscribe("input", 1, &SModelGripperActionServer::analysisCB, this); goal_pub_ = nh_.advertise<GripperOutput>("output", 1); as_.start(); } void SModelGripperActionServer::goalCB() { // Check to see if the gripper is in an active state where it can take goals if (current_reg_state_.gIMC != 0x3) { ROS_WARN("%s could not accept goal because the gripper is not yet active", action_name_.c_str()); return; } GripperCommandGoal current_goal (*(as_.acceptNewGoal())); if (as_.isPreemptRequested()) { as_.setPreempted(); } try { if (current_goal.command.max_effort == 0.0){ ROS_INFO("requested to move gripper with max_effort of 0.0. Defaulting to 70.0"); current_goal.command.max_effort = 70.0; } goal_reg_state_ = goalToRegisterState(current_goal, gripper_params_); goal_pub_.publish(goal_reg_state_); } catch (BadArgumentsError& e) { ROS_INFO("%s No goal issued to gripper", action_name_.c_str()); } } void SModelGripperActionServer::preemptCB() { ROS_INFO("%s: Preempted", action_name_.c_str()); as_.setPreempted(); } void SModelGripperActionServer::analysisCB(const GripperInput::ConstPtr& msg) { current_reg_state_ = *msg; // Check to see if the gripper is in its activated state if (current_reg_state_.gIMC != 0x3) { // Check to see if the gripper is active or if it has been asked to be active if (current_reg_state_.gIMC == 0x0 && goal_reg_state_.rACT != 0x1) { // If it hasn't been asked, active it issueActivation(); } // Otherwise wait for the gripper to activate // TODO: If message delivery isn't guaranteed, then we may want to resend activate return; } if (!as_.isActive()) return; // Check for errors if (current_reg_state_.gFLT) { ROS_WARN("%s faulted with code: %x", action_name_.c_str(), current_reg_state_.gFLT); as_.setAborted(registerStateToResult(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } else if (current_reg_state_.gGTO && current_reg_state_.gIMC == 0x03 && current_reg_state_.gPRA == goal_reg_state_.rPRA && current_reg_state_.gSTA) { // If commanded to move and if at a goal state and if the position request matches the echo'd PR, we're // done with a moveregisterStateToR ROS_INFO("%s succeeded", action_name_.c_str()); as_.setSucceeded(registerStateToResult(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } else { // Publish feedback as_.publishFeedback(registerStateToFeedback(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } } void SModelGripperActionServer::issueActivation() { ROS_INFO("Activating gripper for gripper action server: %s", action_name_.c_str()); GripperOutput out; out.rACT = 0x1; out.rMOD = 0x0; out.rSPA = 128; // other params should be zero goal_reg_state_ = out; goal_pub_.publish(out); } } // end robotiq_action_server namespace <commit_msg>Changing finger speed to default value 128<commit_after>/** * ActionServer interface to the control_msgs/GripperCommand action * for a Robotiq S-Model device */ #include "robotiq_action_server/robotiq_s_model_action_server.h" // To keep the fully qualified names managable //Anonymous namespaces are file local -> sort of like global static objects namespace { using namespace robotiq_action_server; /* This struct is declared for the sole purpose of being used as an exception internally to keep the code clean (i.e. no output params). It is caught by the action_server and should not propogate outwards. If you use these functions yourself, beware. */ struct BadArgumentsError {}; GripperOutput goalToRegisterState(const GripperCommandGoal& goal, const SModelGripperParams& params) { GripperOutput result; result.rACT = 0x1; // active gripper result.rGTO = 0x1; // go to position result.rATR = 0x0; // No emergency release //result.rICS = 1; // individual control of scissor result.rSPA = 128; // finger speed; 80 for this specific case //result.rSPS = 255; // scissor speed if (goal.command.position > params.max_rad_ || goal.command.position < params.min_rad_) { ROS_WARN("Goal gripper rad size is out of range(%f to %f): %f m", params.min_rad_, params.max_rad_, goal.command.position); throw BadArgumentsError(); } if (goal.command.max_effort < params.min_effort_ || goal.command.max_effort > params.max_effort_) { ROS_WARN("Goal gripper effort out of range (%f to %f N): %f N", params.min_effort_, params.max_effort_, goal.command.max_effort); throw BadArgumentsError(); } //The register value for the closed pinch mode is 113, //the minimal register value for the finger is 6 , so wie divide with 107 double dist_per_tick = (params.max_rad_ - params.min_rad_) / 235; double eff_per_tick = (params.max_effort_ - params.min_effort_) / 255; result.rPRA = static_cast<uint8_t>((goal.command.position) / dist_per_tick); result.rFRA = static_cast<uint8_t>((goal.command.max_effort - params.min_effort_) / eff_per_tick); /* Register Value for scissor position: calculatet with the position of fingers (between 6 and 113) multiplied with max scissor position divided by max finger position. I'm not sure why it musst be 212 and 113 and noch 197 and 107, cause the scissor position starts with 15 and the finger position with 6. */ //result.rPRS = static_cast<uint8_t>(result.rPRA*(212.0/113.0)); ROS_INFO("Setting goal position register to %hhu", result.rPRA); ROS_INFO_STREAM("Goal command position: " << goal.command.position); ROS_INFO_STREAM("param min_rad: " << params.min_rad_); ROS_INFO_STREAM("param max_rad: " << params.max_rad_); ROS_INFO_STREAM(goal); return result; } /* This function is templatized because both GripperCommandResult and GripperCommandFeedback consist of the same fields yet have different types. Templates here act as a "duck typing" mechanism to avoid code duplication. */ template<typename T> T registerStateToResultT(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { T result; double dist_per_tick = (params.max_rad_ - params.min_rad_) / 255; double eff_per_tick = (params.max_effort_ - params.min_effort_) / 255; result.position = input.gPOA * dist_per_tick + params.min_rad_; result.effort = input.gCUA * eff_per_tick + params.min_effort_; result.stalled = input.gIMC == 0x1 || input.gIMC == 0x2; result.reached_goal = input.gPOA == goal_pos; return result; } // Inline api-transformers to avoid confusion when reading the action_server source inline GripperCommandResult registerStateToResult(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { return registerStateToResultT<GripperCommandResult>(input, params, goal_pos); } inline GripperCommandFeedback registerStateToFeedback(const GripperInput& input, const SModelGripperParams& params, uint8_t goal_pos) { return registerStateToResultT<GripperCommandFeedback>(input, params, goal_pos); } } // end of anon namespace namespace robotiq_action_server { SModelGripperActionServer::SModelGripperActionServer(const std::string& name, const SModelGripperParams& params) : nh_() , as_(nh_, name, false) , action_name_(name) , gripper_params_(params) { as_.registerGoalCallback(boost::bind(&SModelGripperActionServer::goalCB, this)); as_.registerPreemptCallback(boost::bind(&SModelGripperActionServer::preemptCB, this)); state_sub_ = nh_.subscribe("input", 1, &SModelGripperActionServer::analysisCB, this); goal_pub_ = nh_.advertise<GripperOutput>("output", 1); as_.start(); } void SModelGripperActionServer::goalCB() { // Check to see if the gripper is in an active state where it can take goals if (current_reg_state_.gIMC != 0x3) { ROS_WARN("%s could not accept goal because the gripper is not yet active", action_name_.c_str()); return; } GripperCommandGoal current_goal (*(as_.acceptNewGoal())); if (as_.isPreemptRequested()) { as_.setPreempted(); } try { if (current_goal.command.max_effort == 0.0){ ROS_INFO("requested to move gripper with max_effort of 0.0. Defaulting to 70.0"); current_goal.command.max_effort = 70.0; } goal_reg_state_ = goalToRegisterState(current_goal, gripper_params_); goal_pub_.publish(goal_reg_state_); } catch (BadArgumentsError& e) { ROS_INFO("%s No goal issued to gripper", action_name_.c_str()); } } void SModelGripperActionServer::preemptCB() { ROS_INFO("%s: Preempted", action_name_.c_str()); as_.setPreempted(); } void SModelGripperActionServer::analysisCB(const GripperInput::ConstPtr& msg) { current_reg_state_ = *msg; // Check to see if the gripper is in its activated state if (current_reg_state_.gIMC != 0x3) { // Check to see if the gripper is active or if it has been asked to be active if (current_reg_state_.gIMC == 0x0 && goal_reg_state_.rACT != 0x1) { // If it hasn't been asked, active it issueActivation(); } // Otherwise wait for the gripper to activate // TODO: If message delivery isn't guaranteed, then we may want to resend activate return; } if (!as_.isActive()) return; // Check for errors if (current_reg_state_.gFLT) { ROS_WARN("%s faulted with code: %x", action_name_.c_str(), current_reg_state_.gFLT); as_.setAborted(registerStateToResult(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } else if (current_reg_state_.gGTO && current_reg_state_.gIMC == 0x03 && current_reg_state_.gPRA == goal_reg_state_.rPRA && current_reg_state_.gSTA) { // If commanded to move and if at a goal state and if the position request matches the echo'd PR, we're // done with a moveregisterStateToR ROS_INFO("%s succeeded", action_name_.c_str()); as_.setSucceeded(registerStateToResult(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } else { // Publish feedback as_.publishFeedback(registerStateToFeedback(current_reg_state_, gripper_params_, goal_reg_state_.rPRA)); } } void SModelGripperActionServer::issueActivation() { ROS_INFO("Activating gripper for gripper action server: %s", action_name_.c_str()); GripperOutput out; out.rACT = 0x1; out.rMOD = 0x0; out.rSPA = 128; // other params should be zero goal_reg_state_ = out; goal_pub_.publish(out); } } // end robotiq_action_server namespace <|endoftext|>
<commit_before>#ifndef __STAN__AGRAD__FWD__MATRIX__TO_FVAR_HPP__ #define __STAN__AGRAD__FWD__MATRIX__TO_FVAR_HPP__ #include <vector> #include <stan/math/matrix/Eigen.hpp> #include <stan/math/matrix/typedefs.hpp> #include <stan/agrad/fwd/fvar.hpp> #include <stan/agrad/fwd/matrix/typedefs.hpp> namespace stan { namespace agrad { /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] x A scalar value * @return An automatic differentiation variable with the input value. */ inline fvar<double> to_fvar(const double& x) { return fvar<double>(x); } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] x An automatic differentiation variable. * @return An automatic differentiation variable with the input value. */ inline fvar<double> to_fvar(const fvar<double>& x) { return x; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] m A Matrix with scalars * @return A Matrix with automatic differentiation variables */ inline matrix_fv to_fvar(const stan::math::matrix_d& m) { matrix_fv m_v(m.rows(), m.cols()); for (int j = 0; j < m.cols(); ++j) for (int i = 0; i < m.rows(); ++i) m_v(i,j) = m(i,j); return m_v; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] m A Matrix with automatic differentiation variables. * @return A Matrix with automatic differentiation variables. */ inline matrix_fv to_fvar(const matrix_fv& m) { return m; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] v A Vector of scalars * @return A Vector of automatic differentiation variables with * values of v */ inline vector_fv to_fvar(const stan::math::vector_d& v) { vector_fv v_v(v.size()); for (int i = 0; i < v.size(); ++i) v_v[i] = v[i]; return v_v; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] v A Vector of automatic differentiation variables * @return A Vector of automatic differentiation variables with * values of v */ inline vector_fv to_fvar(const vector_fv& v) { return v; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::var variable with the input value. * * @param[in] rv A row vector of scalars * @return A row vector of automatic differentation variables with * values of rv. */ inline row_vector_fv to_fvar(const stan::math::row_vector_d& rv) { row_vector_fv rv_v(rv.size()); for (int i = 0; i < rv.size(); ++i) rv_v[i] = rv[i]; return rv_v; } /** * Converts argument to an automatic differentiation variable. * * Returns a stan::agrad::fvar variable with the input value. * * @param[in] rv A row vector with automatic differentiation variables * @return A row vector with automatic differentiation variables * with values of rv. */ inline row_vector_fv to_fvar(const row_vector_fv& rv) { return rv; } } } #endif <commit_msg>fixed formatting of to_fvar<commit_after>#ifndef __STAN__AGRAD__FWD__MATRIX__TO_FVAR_HPP__ #define __STAN__AGRAD__FWD__MATRIX__TO_FVAR_HPP__ #include <vector> #include <stan/math/matrix/Eigen.hpp> #include <stan/math/matrix/typedefs.hpp> #include <stan/agrad/fwd/fvar.hpp> #include <stan/agrad/fwd/matrix/typedefs.hpp> namespace stan { namespace agrad { template<typename T> inline fvar<T> to_fvar(const T& x) { return fvar<T>(x); } template<typename T> inline fvar<T> to_fvar(const fvar<T>& x) { return x; } inline matrix_fv to_fvar(const stan::math::matrix_d& m) { matrix_fv m_v(m.rows(), m.cols()); for (int j = 0; j < m.cols(); ++j) for (int i = 0; i < m.rows(); ++i) m_v(i,j) = m(i,j); return m_v; } inline matrix_fv to_fvar(const matrix_fv& m) { return m; } inline vector_fv to_fvar(const stan::math::vector_d& v) { vector_fv v_v(v.size()); for (int i = 0; i < v.size(); ++i) v_v[i] = v[i]; return v_v; } inline vector_fv to_fvar(const vector_fv& v) { return v; } inline row_vector_fv to_fvar(const stan::math::row_vector_d& rv) { row_vector_fv rv_v(rv.size()); for (int i = 0; i < rv.size(); ++i) rv_v[i] = rv[i]; return rv_v; } inline row_vector_fv to_fvar(const row_vector_fv& rv) { return rv; } } } #endif <|endoftext|>
<commit_before>#include "textendanalyzer.h" #include "streamindexer.h" #include "inputstreamreader.h" #include "indexwriter.h" using namespace jstreams; char TextEndAnalyzer::analyze(std::string filename, jstreams::InputStream *in, int depth, StreamIndexer *indexer, Indexable* i) { // very simple algorithm to get out sequences of ascii characters // we actually miss characters that are not on the edge between reads const char* b; int32_t nread = in->read(b, 1024, 0); while (nread > 0) { const char* end = b + nread; const char* p = b; while (p != end) { // find the start of a word while (p < end && !isalpha(*p)) ++p; if (p != end) { const char* e = p + 1; while (e < end && isalpha(*e)) ++e; if (e != end && e-p > 2 && e-p < 30) { std::string field(p, e-p); // printf("%s %s\n", filename.c_str(), field.c_str()); i->addField("content", field); } p = e; } } nread = in->read(b, 1024, 0); } // InputStreamReader reader(in); // i->addStream("content", &reader); return nread; } <commit_msg>Do not extract text from binary files.<commit_after>#include "textendanalyzer.h" #include "streamindexer.h" #include "inputstreamreader.h" #include "indexwriter.h" using namespace jstreams; char TextEndAnalyzer::analyze(std::string filename, jstreams::InputStream *in, int depth, StreamIndexer *indexer, Indexable* i) { // very simple algorithm to get out sequences of ascii characters // we actually miss characters that are not on the edge between reads const char* b; int32_t nread = in->read(b, 1, 0); // check that this is text file const char* end = b + nread; const char* p = b-1; while (++p < end) { if (*p <= 8) { printf("%i\n", *p); return -1; } } while (nread > 0) { end = b + nread; p = b; while (p != end) { // find the start of a word while (p < end && !isalpha(*p)) ++p; if (p != end) { const char* e = p + 1; while (e < end && isalpha(*e)) ++e; if (e != end && e-p > 2 && e-p < 30) { std::string field(p, e-p); // printf("%s %s\n", filename.c_str(), field.c_str()); i->addField("content", field); } p = e; } } nread = in->read(b, 1, 0); } // InputStreamReader reader(in); // i->addStream("content", &reader); return nread; } <|endoftext|>
<commit_before> #include "swganh/command/command_service.h" #include <cctype> #include <cppconn/exception.h> #include <cppconn/connection.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include <cppconn/sqlstring.h> #include "anh/logger.h" #include "anh/crc.h" #include "anh/event_dispatcher.h" #include "anh/database/database_manager_interface.h" #include "anh/service/service_manager.h" #include "swganh/app/swganh_kernel.h" #include "swganh/command/command_filter.h" #include "swganh/messages/controllers/command_queue_enqueue.h" #include "swganh/messages/controllers/command_queue_remove.h" #include "swganh/messages/controllers/combat_action_message.h" #include "swganh/object/creature/creature.h" #include "swganh/object/tangible/tangible.h" #include "swganh/object/object_controller.h" #include "python_command.h" #include "swganh/simulation/simulation_service.h" using namespace anh::app; using namespace anh::service; using namespace std; using namespace swganh::command; using namespace swganh::messages; using namespace swganh::messages::controllers; using namespace swganh::object; using namespace swganh::object::creature; using namespace swganh::object::tangible; using namespace swganh::scripting; using namespace swganh::simulation; using boost::asio::deadline_timer; using boost::posix_time::milliseconds; using swganh::app::SwganhKernel; CommandService::CommandService(SwganhKernel* kernel) : BaseService(kernel) {} ServiceDescription CommandService::GetServiceDescription() { ServiceDescription service_description( "CommandService", "command", "0.1", "127.0.0.1", 0, 0, 0); return service_description; } void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter) { enqueue_filters_.push_back(move(filter)); } void CommandService::AddCommandProcessFilter(CommandFilter&& filter) { process_filters_.push_back(move(filter)); } void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler) { handlers_[command_crc] = move(handler); } void CommandService::EnqueueCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, CommandQueueEnqueue command) { auto properties_iter = command_properties_map_.find(command.command_crc); if (properties_iter == command_properties_map_.end()) { LOG(warning) << "Invalid handler requested: " << hex << command.command_crc; return; } auto handlers_iter = handlers_.find(command.command_crc); if (handlers_iter == handlers_.end()) { LOG(warning) << "No handler for command: " << std::hex << command.command_crc; return; } if (!ValidateCommand(actor, target, command, properties_iter->second, enqueue_filters_)) { LOG(warning) << "Command validation failed"; return; } if (properties_iter->second.add_to_combat_queue && actor->HasState(COMBAT)) { boost::lock_guard<boost::mutex> lg(processor_map_mutex_); auto find_iter = processor_map_.find(actor->GetObjectId()); if (find_iter != processor_map_.end() ) { find_iter->second->PushTask( milliseconds(properties_iter->second.default_time), bind(&CommandService::ProcessCommand, this, actor, target, command, properties_iter->second, handlers_iter->second)); } } else { ProcessCommand( actor, target, command, properties_iter->second, handlers_iter->second); } } void CommandService::HandleCommandQueueEnqueue( const shared_ptr<ObjectController>& controller, const ObjControllerMessage& message) { CommandQueueEnqueue enqueue; enqueue.Deserialize(message.data); auto actor = static_pointer_cast<Creature>(controller->GetObject()); auto target = simulation_service_->GetObjectById<Tangible>(enqueue.target_id); EnqueueCommand(actor, target, move(enqueue)); } void CommandService::HandleCommandQueueRemove( const shared_ptr<ObjectController>& controller, const ObjControllerMessage& message) {} void CommandService::ProcessCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, const swganh::messages::controllers::CommandQueueEnqueue& command, const CommandProperties& properties, const CommandHandler& handler ) { try { if (ValidateCommand(actor, target, command, properties, process_filters_)) { handler(kernel(), actor, target, command); // Convert the default time to a float of seconds. float default_time = command_properties_map_[command.command_crc].default_time / 1000.0f; SendCommandQueueRemove(actor, command.action_counter, default_time, 0, 0); } } catch(const exception& e) { LOG(warning) << "Error Processing Command: " << command_properties_map_[command.command_crc].name << "\n" << e.what(); } } void CommandService::onStart() { LoadProperties(); simulation_service_ = kernel()->GetServiceManager() ->GetService<SimulationService>("SimulationService"); simulation_service_->RegisterControllerHandler(0x00000116, [this] ( const std::shared_ptr<ObjectController>& controller, const swganh::messages::ObjControllerMessage& message) { HandleCommandQueueEnqueue(controller, message); }); simulation_service_->RegisterControllerHandler(0x00000117, [this] ( const std::shared_ptr<ObjectController>& controller, const swganh::messages::ObjControllerMessage& message) { HandleCommandQueueRemove(controller, message); }); auto event_dispatcher = kernel()->GetEventDispatcher(); event_dispatcher->Dispatch( make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties())); event_dispatcher->Subscribe( "ObjectReadyEvent", [this] (shared_ptr<anh::EventInterface> incoming_event) { const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get(); boost::lock_guard<boost::mutex> lg(processor_map_mutex_); processor_map_[object->GetObjectId()].reset(new anh::SimpleDelayedTaskProcessor(kernel()->GetIoService())); }); event_dispatcher->Subscribe( "ObjectRemovedEvent", [this] (shared_ptr<anh::EventInterface> incoming_event) { const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get(); boost::lock_guard<boost::mutex> lg(processor_map_mutex_); processor_map_.erase(object->GetObjectId()); }); } void CommandService::LoadProperties() { try { auto db_manager = kernel()->GetDatabaseManager(); auto conn = db_manager->getConnection("galaxy"); auto statement = unique_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();")); auto result = unique_ptr<sql::ResultSet>(statement->executeQuery()); while (result->next()) { CommandProperties properties; properties.name = result->getString("name"); string tmp = properties.name; transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); properties.name_crc = anh::memcrc(tmp); properties.ability = result->getString("ability"); properties.ability_crc = anh::memcrc(properties.ability); properties.deny_in_states = result->getUInt64("deny_in_states"); properties.script_hook = result->getString("script_hook"); properties.fail_script_hook = result->getString("fail_script_hook"); properties.default_time = result->getUInt64("default_time"); properties.command_group = result->getUInt("command_group"); properties.max_range_to_target = static_cast<float>(result->getDouble("max_range_to_target")); properties.add_to_combat_queue = result->getUInt("add_to_combat_queue"); properties.health_cost = result->getUInt("health_cost"); properties.health_cost_multiplier = result->getUInt("health_cost_multiplier"); properties.action_cost = result->getUInt("action_cost"); properties.action_cost_multiplier = result->getUInt("action_cost_multiplier"); properties.mind_cost = result->getUInt("mind_cost"); properties.mind_cost_multiplier = result->getUInt("mind_cost"); properties.damage_multiplier = static_cast<float>(result->getDouble("damage_multiplier")); properties.delay_multiplier = static_cast<float>(result->getDouble("delay_multiplier")); properties.force_cost = result->getUInt("force_cost"); properties.force_cost_multiplier = result->getUInt("force_cost_multiplier"); properties.animation_crc = result->getUInt("animation_crc"); properties.required_weapon_group = result->getUInt("required_weapon_group"); properties.combat_spam = result->getString("combat_spam"); properties.trail1 = result->getUInt("trail1"); properties.trail2 = result->getUInt("trail2"); properties.allow_in_posture = result->getUInt("allow_in_posture"); properties.health_hit_chance = static_cast<float>(result->getDouble("health_hit_chance")); properties.action_hit_chance = static_cast<float>(result->getDouble("action_hit_chance")); properties.mind_hit_chance = static_cast<float>(result->getDouble("mind_hit_chance")); properties.knockdown_hit_chance = static_cast<float>(result->getDouble("knockdown_chance")); properties.dizzy_hit_chance = static_cast<float>(result->getDouble("dizzy_chance")); properties.blind_chance = static_cast<float>(result->getDouble("blind_chance")); properties.stun_chance = static_cast<float>(result->getDouble("stun_chance")); properties.intimidate_chance = static_cast<float>(result->getDouble("intimidate_chance")); properties.posture_down_chance = static_cast<float>(result->getDouble("posture_down_chance")); properties.extended_range = static_cast<float>(result->getDouble("extended_range")); properties.cone_angle = static_cast<float>(result->getDouble("cone_angle")); properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion"); RegisterCommandScript(properties); command_properties_map_.insert(make_pair(properties.name_crc, move(properties))); } LOG(info) << "Loaded (" << command_properties_map_.size() << ") Commands"; } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } } void CommandService::RegisterCommandScript(const CommandProperties& properties) { if (properties.script_hook.length() != 0) { SetCommandHandler(properties.name_crc, PythonCommand(properties)); } } bool CommandService::ValidateCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, const swganh::messages::controllers::CommandQueueEnqueue& command, const CommandProperties& command_properties, const std::vector<CommandFilter>& filters) { tuple<bool, uint32_t, uint32_t> result; bool all_run = all_of( begin(filters), end(filters), [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool { result = filter(actor, target, command, command_properties); return get<0>(result); }); if (!all_run) { SendCommandQueueRemove(actor, command.action_counter, 0.0f, get<1>(result), get<2>(result)); } return all_run; } void CommandService::SendCommandQueueRemove( const shared_ptr<Creature>& actor, uint32_t action_counter, float default_time_sec, uint32_t error, uint32_t action) { CommandQueueRemove remove; remove.action_counter = action_counter; remove.timer = default_time_sec; remove.error = error; remove.action = action; actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove)); } <commit_msg>Replacing command service's load properties with the datatable reader. Still needs more work to match the client file structure.<commit_after> #include "swganh/command/command_service.h" #include <cctype> #include <cppconn/exception.h> #include <cppconn/connection.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #include <cppconn/sqlstring.h> #include "anh/logger.h" #include "anh/crc.h" #include "anh/event_dispatcher.h" #include "anh/database/database_manager_interface.h" #include "anh/service/service_manager.h" #include "swganh/app/swganh_kernel.h" #include "swganh/command/command_filter.h" #include "swganh/messages/controllers/command_queue_enqueue.h" #include "swganh/messages/controllers/command_queue_remove.h" #include "swganh/messages/controllers/combat_action_message.h" #include "swganh/object/creature/creature.h" #include "swganh/object/tangible/tangible.h" #include "swganh/object/object_controller.h" #include "python_command.h" #include "swganh/simulation/simulation_service.h" #include "swganh/tre/tre_archive.h" #include "swganh/tre/readers/datatable_reader.h" using namespace anh::app; using namespace anh::service; using namespace std; using namespace swganh::command; using namespace swganh::messages; using namespace swganh::messages::controllers; using namespace swganh::object; using namespace swganh::object::creature; using namespace swganh::object::tangible; using namespace swganh::scripting; using namespace swganh::simulation; using boost::asio::deadline_timer; using boost::posix_time::milliseconds; using swganh::app::SwganhKernel; using swganh::tre::readers::DatatableReader; CommandService::CommandService(SwganhKernel* kernel) : BaseService(kernel) {} ServiceDescription CommandService::GetServiceDescription() { ServiceDescription service_description( "CommandService", "command", "0.1", "127.0.0.1", 0, 0, 0); return service_description; } void CommandService::AddCommandEnqueueFilter(CommandFilter&& filter) { enqueue_filters_.push_back(move(filter)); } void CommandService::AddCommandProcessFilter(CommandFilter&& filter) { process_filters_.push_back(move(filter)); } void CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler) { handlers_[command_crc] = move(handler); } void CommandService::EnqueueCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, CommandQueueEnqueue command) { auto properties_iter = command_properties_map_.find(command.command_crc); if (properties_iter == command_properties_map_.end()) { LOG(warning) << "Invalid handler requested: " << hex << command.command_crc; return; } auto handlers_iter = handlers_.find(command.command_crc); if (handlers_iter == handlers_.end()) { LOG(warning) << "No handler for command: " << std::hex << command.command_crc; return; } if (!ValidateCommand(actor, target, command, properties_iter->second, enqueue_filters_)) { LOG(warning) << "Command validation failed"; return; } if (properties_iter->second.add_to_combat_queue && actor->HasState(COMBAT)) { boost::lock_guard<boost::mutex> lg(processor_map_mutex_); auto find_iter = processor_map_.find(actor->GetObjectId()); if (find_iter != processor_map_.end() ) { find_iter->second->PushTask( milliseconds(properties_iter->second.default_time), bind(&CommandService::ProcessCommand, this, actor, target, command, properties_iter->second, handlers_iter->second)); } } else { ProcessCommand( actor, target, command, properties_iter->second, handlers_iter->second); } } void CommandService::HandleCommandQueueEnqueue( const shared_ptr<ObjectController>& controller, const ObjControllerMessage& message) { CommandQueueEnqueue enqueue; enqueue.Deserialize(message.data); auto actor = static_pointer_cast<Creature>(controller->GetObject()); auto target = simulation_service_->GetObjectById<Tangible>(enqueue.target_id); EnqueueCommand(actor, target, move(enqueue)); } void CommandService::HandleCommandQueueRemove( const shared_ptr<ObjectController>& controller, const ObjControllerMessage& message) {} void CommandService::ProcessCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, const swganh::messages::controllers::CommandQueueEnqueue& command, const CommandProperties& properties, const CommandHandler& handler ) { try { if (ValidateCommand(actor, target, command, properties, process_filters_)) { handler(kernel(), actor, target, command); // Convert the default time to a float of seconds. float default_time = command_properties_map_[command.command_crc].default_time / 1000.0f; SendCommandQueueRemove(actor, command.action_counter, default_time, 0, 0); } } catch(const exception& e) { LOG(warning) << "Error Processing Command: " << command_properties_map_[command.command_crc].name << "\n" << e.what(); } } void CommandService::onStart() { LoadProperties(); simulation_service_ = kernel()->GetServiceManager() ->GetService<SimulationService>("SimulationService"); simulation_service_->RegisterControllerHandler(0x00000116, [this] ( const std::shared_ptr<ObjectController>& controller, const swganh::messages::ObjControllerMessage& message) { HandleCommandQueueEnqueue(controller, message); }); simulation_service_->RegisterControllerHandler(0x00000117, [this] ( const std::shared_ptr<ObjectController>& controller, const swganh::messages::ObjControllerMessage& message) { HandleCommandQueueRemove(controller, message); }); auto event_dispatcher = kernel()->GetEventDispatcher(); event_dispatcher->Dispatch( make_shared<anh::ValueEvent<CommandPropertiesMap>>("CommandServiceReady", GetCommandProperties())); event_dispatcher->Subscribe( "ObjectReadyEvent", [this] (shared_ptr<anh::EventInterface> incoming_event) { const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get(); boost::lock_guard<boost::mutex> lg(processor_map_mutex_); processor_map_[object->GetObjectId()].reset(new anh::SimpleDelayedTaskProcessor(kernel()->GetIoService())); }); event_dispatcher->Subscribe( "ObjectRemovedEvent", [this] (shared_ptr<anh::EventInterface> incoming_event) { const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get(); boost::lock_guard<boost::mutex> lg(processor_map_mutex_); processor_map_.erase(object->GetObjectId()); }); } void CommandService::LoadProperties() { try { auto tre_archive = kernel()->GetTreArchive(); DatatableReader reader(tre_archive->GetResource("datatables/command/command_table.iff")); do { auto row = reader.GetRow(); CommandProperties properties; properties.name = row["commandName"]->GetValue<string>(); string tmp = properties.name; transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); properties.name_crc = anh::memcrc(tmp); //properties.default_priority = row["defaultPriority"]->GetValue<int>(); //properties.default_time = row["defaultTime"]->GetValue<float>(); properties.ability = row["characterAbility"]->GetValue<string>(); properties.ability_crc = anh::memcrc(properties.ability); properties.add_to_combat_queue = row["addToCombatQueue"]->GetValue<int>(); command_properties_map_.insert(make_pair(properties.name_crc, move(properties))); } while(reader.Next()); //auto db_manager = kernel()->GetDatabaseManager(); // //auto conn = db_manager->getConnection("galaxy"); //auto statement = unique_ptr<sql::PreparedStatement>(conn->prepareStatement("CALL sp_LoadCommandProperties();")); // //auto result = unique_ptr<sql::ResultSet>(statement->executeQuery()); // //while (result->next()) //{ // CommandProperties properties; // // properties.name = result->getString("name"); // // string tmp = properties.name; // transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower); // properties.name_crc = anh::memcrc(tmp); // // properties.ability = result->getString("ability"); // properties.ability_crc = anh::memcrc(properties.ability); // properties.deny_in_states = result->getUInt64("deny_in_states"); // properties.script_hook = result->getString("script_hook"); // properties.fail_script_hook = result->getString("fail_script_hook"); // properties.default_time = result->getUInt64("default_time"); // properties.command_group = result->getUInt("command_group"); // properties.max_range_to_target = static_cast<float>(result->getDouble("max_range_to_target")); // properties.add_to_combat_queue = result->getUInt("add_to_combat_queue"); // properties.health_cost = result->getUInt("health_cost"); // properties.health_cost_multiplier = result->getUInt("health_cost_multiplier"); // properties.action_cost = result->getUInt("action_cost"); // properties.action_cost_multiplier = result->getUInt("action_cost_multiplier"); // properties.mind_cost = result->getUInt("mind_cost"); // properties.mind_cost_multiplier = result->getUInt("mind_cost"); // properties.damage_multiplier = static_cast<float>(result->getDouble("damage_multiplier")); // properties.delay_multiplier = static_cast<float>(result->getDouble("delay_multiplier")); // properties.force_cost = result->getUInt("force_cost"); // properties.force_cost_multiplier = result->getUInt("force_cost_multiplier"); // properties.animation_crc = result->getUInt("animation_crc"); // properties.required_weapon_group = result->getUInt("required_weapon_group"); // properties.combat_spam = result->getString("combat_spam"); // properties.trail1 = result->getUInt("trail1"); // properties.trail2 = result->getUInt("trail2"); // properties.allow_in_posture = result->getUInt("allow_in_posture"); // properties.health_hit_chance = static_cast<float>(result->getDouble("health_hit_chance")); // properties.action_hit_chance = static_cast<float>(result->getDouble("action_hit_chance")); // properties.mind_hit_chance = static_cast<float>(result->getDouble("mind_hit_chance")); // properties.knockdown_hit_chance = static_cast<float>(result->getDouble("knockdown_chance")); // properties.dizzy_hit_chance = static_cast<float>(result->getDouble("dizzy_chance")); // properties.blind_chance = static_cast<float>(result->getDouble("blind_chance")); // properties.stun_chance = static_cast<float>(result->getDouble("stun_chance")); // properties.intimidate_chance = static_cast<float>(result->getDouble("intimidate_chance")); // properties.posture_down_chance = static_cast<float>(result->getDouble("posture_down_chance")); // properties.extended_range = static_cast<float>(result->getDouble("extended_range")); // properties.cone_angle = static_cast<float>(result->getDouble("cone_angle")); // properties.deny_in_locomotion = result->getUInt64("deny_in_locomotion"); // // RegisterCommandScript(properties); // // command_properties_map_.insert(make_pair(properties.name_crc, move(properties))); //} LOG(info) << "Loaded (" << reader.CountRows() /*command_properties_map_.size()*/ << ") Commands"; } catch(sql::SQLException &e) { LOG(error) << "SQLException at " << __FILE__ << " (" << __LINE__ << ": " << __FUNCTION__ << ")"; LOG(error) << "MySQL Error: (" << e.getErrorCode() << ": " << e.getSQLState() << ") " << e.what(); } } void CommandService::RegisterCommandScript(const CommandProperties& properties) { if (properties.script_hook.length() != 0) { SetCommandHandler(properties.name_crc, PythonCommand(properties)); } } bool CommandService::ValidateCommand( const shared_ptr<Creature>& actor, const shared_ptr<Tangible>& target, const swganh::messages::controllers::CommandQueueEnqueue& command, const CommandProperties& command_properties, const std::vector<CommandFilter>& filters) { tuple<bool, uint32_t, uint32_t> result; bool all_run = all_of( begin(filters), end(filters), [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool { result = filter(actor, target, command, command_properties); return get<0>(result); }); if (!all_run) { SendCommandQueueRemove(actor, command.action_counter, 0.0f, get<1>(result), get<2>(result)); } return all_run; } void CommandService::SendCommandQueueRemove( const shared_ptr<Creature>& actor, uint32_t action_counter, float default_time_sec, uint32_t error, uint32_t action) { CommandQueueRemove remove; remove.action_counter = action_counter; remove.timer = default_time_sec; remove.error = error; remove.action = action; actor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove)); } <|endoftext|>
<commit_before>#include "LIBGPU.H" #define GL_GLEXT_PROTOTYPES 1 #include <GL/glew.h> #include <SDL.h> #include <SDL_opengl.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <LIBETC.H> #include "EMULATOR.H" #include "EMULATOR_GLOBALS.H" #define POLY_TAG_USE_ADDR (0) #define HACK_CLEAR_DRAW_AREA (1) #define ENABLE_BLEND (0) unsigned short vram[1024 * 512]; DISPENV word_33BC; DRAWENV word_unknown00;//Guessed int dword_3410 = 0; char byte_3352 = 0; unsigned long terminator = -1; void(*drawsync_callback)(void) = NULL; void* off_3348[]= { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; int ClearImage(RECT16* rect, u_char r, u_char g, u_char b) { Emulator_CheckTextureIntersection(rect); for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* pixel = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { pixel[0] = 1 << 15 | ((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3)); } } } return 0; } int DrawSync(int mode) { if (drawsync_callback != NULL) { drawsync_callback(); } return 0; } int LoadImagePSX(RECT16* rect, u_long* p) { Emulator_CheckTextureIntersection(rect); unsigned short* dst = (unsigned short*)p; for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* src = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { src[0] = *dst++; } } } #if _DEBUG FILE* f = fopen("VRAM.BIN", "wb"); fwrite(&vram[0], 1, 1024 * 512 * 2, f); fclose(f); #endif return 0; } int MoveImage(RECT16* rect, int x, int y) { #if 0//TODO for (int sy = rect->y; sy < 512; sy++) { for (int sx = rect->x; sx < 1024; sx++) { unsigned short* src = vram + (sy * 1024 + sx); unsigned short* dst = vram + (y * 1024 + x); if (sx >= rect->x && sx < rect->x + rect->w && sy >= rect->y && sy < rect->y + rect->h) { *dst++ = *src++; } } } #endif return 0; } int ResetGraph(int mode) { UNIMPLEMENTED(); return 0; } int SetGraphDebug(int level) { UNIMPLEMENTED(); return 0; } int StoreImage(RECT16 * RECT16, u_long * p) { UNIMPLEMENTED(); return 0; } u_long* ClearOTag(u_long* ot, int n) { //Nothing to do here. if (n == 0) return NULL; //Last is special terminator ot[n-1] = (unsigned long)&terminator; if (n > 1) { for (int i = n-2; i > -1; i--) { ot[i] = (unsigned long)&ot[i+1]; } } return NULL; } u_long* ClearOTagR(u_long* ot, int n) { //Nothing to do here. if (n == 0) return NULL; //First is special terminator ot[0] = (unsigned long)&terminator; if (n > 1) { for (int i = 1; i < n; i++) { ot[i] = (unsigned long)&ot[i - 1]; } } return NULL; } void SetDispMask(int mask) { UNIMPLEMENTED(); } DISPENV* GetDispEnv(DISPENV* env)//(F) { memcpy(env, &word_33BC, sizeof(DISPENV)); return env; } DISPENV* PutDispEnv(DISPENV* env)//To Finish { memcpy((char*)&word_33BC, env, sizeof(DISPENV)); return 0; } DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F) { env->disp.x = x; env->disp.y = y; env->disp.w = w; env->screen.x = 0; env->screen.y = 0; env->screen.w = 0; env->screen.h = 0; env->isrgb24 = 0; env->isinter = 0; env->pad1 = 0; env->pad0 = 0; env->disp.h = h; return 0; } DRAWENV* PutDrawEnv(DRAWENV* env)//Guessed { memcpy((char*)&word_unknown00, env, sizeof(DRAWENV)); return 0; } DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F) { env->clip.x = x; env->clip.y = y; env->clip.w = w; env->tw.x = 0; env->tw.y = 0; env->tw.w = 0; env->tw.h = 0; env->r0 = 0; env->g0 = 0; env->b0 = 0; env->dtd = 1; env->clip.h = h; if (GetVideoMode() == 0) { env->dfe = h < 0x121 ? 1 : 0; } else { env->dfe = h < 0x101 ? 1 : 0; } env->ofs[0] = x; env->ofs[1] = y; env->tpage = 10; env->isbg = 0; return env; } u_long DrawSyncCallback(void(*func)(void)) { drawsync_callback = func; return 0; } void DrawOTagEnv(u_long* p, DRAWENV* env) { PutDrawEnv(env); #if HACK_CLEAR_DRAW_AREA ClearImage(&env->clip, 0, 0, 0); #endif GLuint fbo = 0; if (p != NULL && *p != NULL) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1024, 0, 512, -1, 1); glViewport(0, 0, 1024, 512); glEnable(GL_TEXTURE_2D); Emulator_GenerateFrameBuffer(fbo); Emulator_GenerateFrameBufferTexture(); P_TAG* pTag = (P_TAG*)p; do { switch (pTag->code & ~3) { case 0x00: // null poly break; case 0x20: // POLY_F3 goto unhandled; case 0x24: // POLY_FT3 goto unhandled; case 0x28: // POLY_F4 { //Emulator_SetBlendMode((pTag->code & 2) != 0); glBindTexture(GL_TEXTURE_2D, nullWhiteTexture); POLY_F4* poly = (POLY_F4*)pTag; glBegin(GL_QUADS); glColor3ubv(&poly->r0); glTexCoord2f(0.0f, 0.0f); glVertex2f(poly->x0, poly->y0); glTexCoord2f(1.0f, 0.0f); glVertex2f(poly->x1, poly->y1); glTexCoord2f(0.0f, 1.0f); glVertex2f(poly->x3, poly->y3); glTexCoord2f(1.0f, 1.0f); glVertex2f(poly->x2, poly->y2); glEnd(); break; } case 0x2C: // POLY_FT4 { POLY_FT4* poly = (POLY_FT4*)pTag; Emulator_GenerateAndBindTpage(poly->tpage, poly->clut); glBegin(GL_TRIANGLES); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); //glColor3ub(poly->r0, poly->g0, poly->b0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u1)), 1.0f / (256.0f / (float)(poly->v1))); glVertex2f(poly->x1, poly->y1); //glColor3ub(poly->r0, poly->g0, poly->b0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); //glColor3ubv(&poly->r3); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); //glColor3ubv(&poly->r2); glEnd(); break; } case 0x30: // POLY_G3 goto unhandled; case 0x34: // POLY_GT3 goto unhandled; case 0x38: // POLY_G4 goto unhandled; case 0x3C: // POLY_GT4 { POLY_GT4* poly = (POLY_GT4*)pTag; Emulator_GenerateAndBindTpage(poly->tpage, poly->clut); glBegin(GL_QUADS); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); glColor3ubv(&poly->r1); glTexCoord2f(1.0f / (256.0f / (float)(poly->u1)), 1.0f / (256.0f / (float)(poly->v1))); glVertex2f(poly->x1, poly->y1); glColor3ubv(&poly->r3); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); glColor3ubv(&poly->r2); glTexCoord2f(1.0f / (256.0f / (float)(poly->u2)), 1.0f / (256.0f / (float)(poly->v2))); glVertex2f(poly->x2, poly->y2); glEnd(); break; } case 0x40: // LINE_F2 goto unhandled; case 0x50: // LINE_G2 { //Emulator_SetBlendMode(-1); glBindTexture(GL_TEXTURE_2D, nullWhiteTexture); LINE_G2* poly = (LINE_G2*)pTag; glLineWidth(1); glColor3ubv(&poly->r0); glBegin(GL_LINES); glVertex2f(poly->x0, poly->y0); glVertex2f(poly->x1, poly->y1); glEnd(); break; } case 0x60: // TILE goto unhandled; case 0x64: // SPRT goto unhandled; case 0x68: // TILE_1 goto unhandled; case 0x70: // TILE_8 goto unhandled; case 0x74: // SPRT_8 goto unhandled; case 0x78: // TILE_16 goto unhandled; case 0x7C: // SPRT_16 goto unhandled; case 0xE1: // TPAGE { unsigned short tpage = ((unsigned short*)pTag)[2]; Emulator_GenerateAndBindTpage(tpage, 0); break; } unhandled: default: eprinterr("Unhandled primitive type: %02X\n", pTag->code); //Unhandled poly break; } //p = (unsigned long*)((uintptr_t)pTag - ((pTag->len * 4) + 4)); pTag = (P_TAG*)pTag->addr; //p = (unsigned long*)*p; //Reset for vertex colours glColor4f(1.0f, 1.0f, 1.0f, 1.0f); }while ((unsigned long*)pTag != &terminator); Emulator_DestroyLastVRAMTexture(); Emulator_DeleteFrameBufferTexture(); glViewport(0, 0, windowWidth, windowHeight); glPopMatrix(); Emulator_DestroyFrameBuffer(fbo); } Emulator_CheckTextureIntersection(&env->clip); } <commit_msg>fix quad drawing<commit_after>#include "LIBGPU.H" #define GL_GLEXT_PROTOTYPES 1 #include <GL/glew.h> #include <SDL.h> #include <SDL_opengl.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <LIBETC.H> #include "EMULATOR.H" #include "EMULATOR_GLOBALS.H" #define POLY_TAG_USE_ADDR (0) #define HACK_CLEAR_DRAW_AREA (1) #define ENABLE_BLEND (0) unsigned short vram[1024 * 512]; DISPENV word_33BC; DRAWENV word_unknown00;//Guessed int dword_3410 = 0; char byte_3352 = 0; unsigned long terminator = -1; void(*drawsync_callback)(void) = NULL; void* off_3348[]= { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; int ClearImage(RECT16* rect, u_char r, u_char g, u_char b) { Emulator_CheckTextureIntersection(rect); for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* pixel = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { pixel[0] = 1 << 15 | ((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3)); } } } return 0; } int DrawSync(int mode) { if (drawsync_callback != NULL) { drawsync_callback(); } return 0; } int LoadImagePSX(RECT16* rect, u_long* p) { Emulator_CheckTextureIntersection(rect); unsigned short* dst = (unsigned short*)p; for (int y = rect->y; y < 512; y++) { for (int x = rect->x; x < 1024; x++) { unsigned short* src = vram + (y * 1024 + x); if (x >= rect->x && x < rect->x + rect->w && y >= rect->y && y < rect->y + rect->h) { src[0] = *dst++; } } } #if _DEBUG FILE* f = fopen("VRAM.BIN", "wb"); fwrite(&vram[0], 1, 1024 * 512 * 2, f); fclose(f); #endif return 0; } int MoveImage(RECT16* rect, int x, int y) { #if 0//TODO for (int sy = rect->y; sy < 512; sy++) { for (int sx = rect->x; sx < 1024; sx++) { unsigned short* src = vram + (sy * 1024 + sx); unsigned short* dst = vram + (y * 1024 + x); if (sx >= rect->x && sx < rect->x + rect->w && sy >= rect->y && sy < rect->y + rect->h) { *dst++ = *src++; } } } #endif return 0; } int ResetGraph(int mode) { UNIMPLEMENTED(); return 0; } int SetGraphDebug(int level) { UNIMPLEMENTED(); return 0; } int StoreImage(RECT16 * RECT16, u_long * p) { UNIMPLEMENTED(); return 0; } u_long* ClearOTag(u_long* ot, int n) { //Nothing to do here. if (n == 0) return NULL; //Last is special terminator ot[n-1] = (unsigned long)&terminator; if (n > 1) { for (int i = n-2; i > -1; i--) { ot[i] = (unsigned long)&ot[i+1]; } } return NULL; } u_long* ClearOTagR(u_long* ot, int n) { //Nothing to do here. if (n == 0) return NULL; //First is special terminator ot[0] = (unsigned long)&terminator; if (n > 1) { for (int i = 1; i < n; i++) { ot[i] = (unsigned long)&ot[i - 1]; } } return NULL; } void SetDispMask(int mask) { UNIMPLEMENTED(); } DISPENV* GetDispEnv(DISPENV* env)//(F) { memcpy(env, &word_33BC, sizeof(DISPENV)); return env; } DISPENV* PutDispEnv(DISPENV* env)//To Finish { memcpy((char*)&word_33BC, env, sizeof(DISPENV)); return 0; } DISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)//(F) { env->disp.x = x; env->disp.y = y; env->disp.w = w; env->screen.x = 0; env->screen.y = 0; env->screen.w = 0; env->screen.h = 0; env->isrgb24 = 0; env->isinter = 0; env->pad1 = 0; env->pad0 = 0; env->disp.h = h; return 0; } DRAWENV* PutDrawEnv(DRAWENV* env)//Guessed { memcpy((char*)&word_unknown00, env, sizeof(DRAWENV)); return 0; } DRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)//(F) { env->clip.x = x; env->clip.y = y; env->clip.w = w; env->tw.x = 0; env->tw.y = 0; env->tw.w = 0; env->tw.h = 0; env->r0 = 0; env->g0 = 0; env->b0 = 0; env->dtd = 1; env->clip.h = h; if (GetVideoMode() == 0) { env->dfe = h < 0x121 ? 1 : 0; } else { env->dfe = h < 0x101 ? 1 : 0; } env->ofs[0] = x; env->ofs[1] = y; env->tpage = 10; env->isbg = 0; return env; } u_long DrawSyncCallback(void(*func)(void)) { drawsync_callback = func; return 0; } void DrawOTagEnv(u_long* p, DRAWENV* env) { PutDrawEnv(env); #if HACK_CLEAR_DRAW_AREA ClearImage(&env->clip, 0, 0, 0); #endif GLuint fbo = 0; if (p != NULL && *p != NULL) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 1024, 0, 512, -1, 1); glViewport(0, 0, 1024, 512); glEnable(GL_TEXTURE_2D); Emulator_GenerateFrameBuffer(fbo); Emulator_GenerateFrameBufferTexture(); P_TAG* pTag = (P_TAG*)p; do { switch (pTag->code & ~3) { case 0x00: // null poly break; case 0x20: // POLY_F3 goto unhandled; case 0x24: // POLY_FT3 goto unhandled; case 0x28: // POLY_F4 { //Emulator_SetBlendMode((pTag->code & 2) != 0); glBindTexture(GL_TEXTURE_2D, nullWhiteTexture); POLY_F4* poly = (POLY_F4*)pTag; glBegin(GL_QUADS); glColor3ubv(&poly->r0); glTexCoord2f(0.0f, 0.0f); glVertex2f(poly->x0, poly->y0); glTexCoord2f(1.0f, 0.0f); glVertex2f(poly->x1, poly->y1); glTexCoord2f(0.0f, 1.0f); glVertex2f(poly->x3, poly->y3); glTexCoord2f(1.0f, 1.0f); glVertex2f(poly->x2, poly->y2); glEnd(); break; } case 0x2C: // POLY_FT4 { POLY_FT4* poly = (POLY_FT4*)pTag; Emulator_GenerateAndBindTpage(poly->tpage, poly->clut); glBegin(GL_TRIANGLES); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); //glColor3ub(poly->r0, poly->g0, poly->b0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u1)), 1.0f / (256.0f / (float)(poly->v1))); glVertex2f(poly->x1, poly->y1); //glColor3ub(poly->r0, poly->g0, poly->b0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u2)), 1.0f / (256.0f / (float)(poly->v2))); glVertex2f(poly->x2, poly->y2); //glColor3ubv(&poly->r3); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); //glColor3ubv(&poly->r2); glEnd(); break; } case 0x30: // POLY_G3 goto unhandled; case 0x34: // POLY_GT3 goto unhandled; case 0x38: // POLY_G4 goto unhandled; case 0x3C: // POLY_GT4 { POLY_GT4* poly = (POLY_GT4*)pTag; Emulator_GenerateAndBindTpage(poly->tpage, poly->clut); glBegin(GL_QUADS); glColor3ubv(&poly->r0); glTexCoord2f(1.0f / (256.0f / (float)(poly->u0)), 1.0f / (256.0f / (float)(poly->v0))); glVertex2f(poly->x0, poly->y0); glColor3ubv(&poly->r1); glTexCoord2f(1.0f / (256.0f / (float)(poly->u1)), 1.0f / (256.0f / (float)(poly->v1))); glVertex2f(poly->x1, poly->y1); glColor3ubv(&poly->r3); glTexCoord2f(1.0f / (256.0f / (float)(poly->u3)), 1.0f / (256.0f / (float)(poly->v3))); glVertex2f(poly->x3, poly->y3); glColor3ubv(&poly->r2); glTexCoord2f(1.0f / (256.0f / (float)(poly->u2)), 1.0f / (256.0f / (float)(poly->v2))); glVertex2f(poly->x2, poly->y2); glEnd(); break; } case 0x40: // LINE_F2 goto unhandled; case 0x50: // LINE_G2 { //Emulator_SetBlendMode(-1); glBindTexture(GL_TEXTURE_2D, nullWhiteTexture); LINE_G2* poly = (LINE_G2*)pTag; glLineWidth(1); glColor3ubv(&poly->r0); glBegin(GL_LINES); glVertex2f(poly->x0, poly->y0); glVertex2f(poly->x1, poly->y1); glEnd(); break; } case 0x60: // TILE goto unhandled; case 0x64: // SPRT goto unhandled; case 0x68: // TILE_1 goto unhandled; case 0x70: // TILE_8 goto unhandled; case 0x74: // SPRT_8 goto unhandled; case 0x78: // TILE_16 goto unhandled; case 0x7C: // SPRT_16 goto unhandled; case 0xE1: // TPAGE { unsigned short tpage = ((unsigned short*)pTag)[2]; Emulator_GenerateAndBindTpage(tpage, 0); break; } unhandled: default: eprinterr("Unhandled primitive type: %02X\n", pTag->code); //Unhandled poly break; } //p = (unsigned long*)((uintptr_t)pTag - ((pTag->len * 4) + 4)); pTag = (P_TAG*)pTag->addr; //p = (unsigned long*)*p; //Reset for vertex colours glColor4f(1.0f, 1.0f, 1.0f, 1.0f); }while ((unsigned long*)pTag != &terminator); Emulator_DestroyLastVRAMTexture(); Emulator_DeleteFrameBufferTexture(); glViewport(0, 0, windowWidth, windowHeight); glPopMatrix(); Emulator_DestroyFrameBuffer(fbo); } Emulator_CheckTextureIntersection(&env->clip); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/command_line.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/ipc_logging.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread(Thread::Options options) : Thread("Chrome_ChildThread"), owner_loop_(MessageLoop::current()), in_send_(0), options_(options) { DCHECK(owner_loop_); channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue( switches::kProcessChannelID); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { #if defined(OS_WIN) // TODO(port): calling this connects an, otherwise disconnected, subgraph // of symbols, causing huge numbers of linker errors. webkit_glue::SetUserAgent(WideToUTF8( CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent))); #endif } } ChildThread::~ChildThread() { } bool ChildThread::Run() { return StartWithOptions(options_); } void ChildThread::OnChannelError() { owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } in_send_++; bool rv = channel_->Send(msg); in_send_--; return rv; } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } ChildThread* ChildThread::current() { return ChildProcess::current()->child_thread(); } void ChildThread::Init() { channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif } void ChildThread::CleanUp() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // Need to destruct the SyncChannel to the browser before we go away because // it caches a pointer to this thread. channel_.reset(); } <commit_msg>Fix release build break<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/command_line.h" #include "base/string_util.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/ipc_logging.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread(Thread::Options options) : Thread("Chrome_ChildThread"), owner_loop_(MessageLoop::current()), in_send_(0), options_(options) { DCHECK(owner_loop_); channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue( switches::kProcessChannelID); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { #if defined(OS_WIN) // TODO(port): calling this connects an, otherwise disconnected, subgraph // of symbols, causing huge numbers of linker errors. webkit_glue::SetUserAgent(WideToUTF8( CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent))); #endif } } ChildThread::~ChildThread() { } bool ChildThread::Run() { return StartWithOptions(options_); } void ChildThread::OnChannelError() { owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } in_send_++; bool rv = channel_->Send(msg); in_send_--; return rv; } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } ChildThread* ChildThread::current() { return ChildProcess::current()->child_thread(); } void ChildThread::Init() { channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif } void ChildThread::CleanUp() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // Need to destruct the SyncChannel to the browser before we go away because // it caches a pointer to this thread. channel_.reset(); } <|endoftext|>