hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
20dd0e723bee057be45aa79aa81930c73d7a233a
193
cpp
C++
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
07-Algorithm STL/01-Iterator/Pair.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<iostream> #include<utility> using namespace std; int main() { pair<int,int>p(10,20), p1(30,40); cout<<(p==p1)<<endl; cout<<(p!=p1)<<endl; cout<<(p>p1)<<endl; cout<<(p<p1)<<endl; }
17.545455
34
0.611399
ShreyashRoyzada
22134f220212bbc2e29cea9a2a7dcdbc96c053ef
1,811
cpp
C++
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
source/ff.dxgi/source/data_blob.cpp
spadapet/ff-engine
244f653c5a25f22f2222842f32608f1101150c6f
[ "MIT" ]
null
null
null
#include "pch.h" #include "data_blob.h" ff::dxgi::data_blob_dx::data_blob_dx(ID3DBlob* blob) : data_blob_dx(blob, 0, blob->GetBufferSize()) {} ff::dxgi::data_blob_dx::data_blob_dx(ID3DBlob* blob, size_t offset, size_t size) : blob(blob) , offset(offset) , size_(size) { assert(blob && offset + size <= blob->GetBufferSize()); } size_t ff::dxgi::data_blob_dx::size() const { return this->size_; } const uint8_t* ff::dxgi::data_blob_dx::data() const { return reinterpret_cast<const uint8_t*>(this->blob->GetBufferPointer()) + this->offset; } std::shared_ptr<ff::data_base> ff::dxgi::data_blob_dx::subdata(size_t offset, size_t size) const { assert(offset + size <= this->size_); return std::make_shared<data_blob_dx>(this->blob.Get(), this->offset + offset, size); } ff::dxgi::data_blob_dxtex::data_blob_dxtex(DirectX::Blob&& blob) : data_blob_dxtex(std::move(blob), 0, blob.GetBufferSize()) {} ff::dxgi::data_blob_dxtex::data_blob_dxtex(DirectX::Blob&& blob, size_t offset, size_t size) : data_blob_dxtex(std::make_shared<DirectX::Blob>(std::move(blob)), offset, size) {} ff::dxgi::data_blob_dxtex::data_blob_dxtex(std::shared_ptr<DirectX::Blob> blob, size_t offset, size_t size) : blob(blob) , offset(offset) , size_(size) { assert(offset + size <= this->blob->GetBufferSize()); } size_t ff::dxgi::data_blob_dxtex::size() const { return this->size_; } const uint8_t* ff::dxgi::data_blob_dxtex::data() const { return reinterpret_cast<const uint8_t*>(this->blob->GetBufferPointer()) + this->offset; } std::shared_ptr<ff::data_base> ff::dxgi::data_blob_dxtex::subdata(size_t offset, size_t size) const { assert(offset + size <= this->size_); return std::make_shared<data_blob_dxtex>(this->blob, this->offset + offset, size); }
28.746032
107
0.696853
spadapet
2217863310194bc24097740123343683c502dd9a
3,863
hpp
C++
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/housys/include/hou/sys/display_mode.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_SYS_DISPLAY_MODE_HPP #define HOU_SYS_DISPLAY_MODE_HPP #include "hou/sys/display_format.hpp" #include "hou/sys/sys_config.hpp" #include "hou/mth/matrix.hpp" #include <ostream> #include <vector> namespace hou { /** * Represents a display mode: resolution, format, and refresh rate. */ class HOU_SYS_API display_mode { public: /** * Creates a display_mode object with all fields initialized to zero. */ display_mode(); /** * Creates a display_mode object. * * \param size the size. * * \param df the display format. * * \param refresh_rate the refresh_rate. */ display_mode(const vec2u& size, display_format df, uint refresh_rate) noexcept; /** * Gets the size. * * \return the size. */ const vec2u& get_size() const noexcept; /** * Sets the size. * * \param size the size. */ void set_size(const vec2u& size) noexcept; /** * Gets the pixel format. * * \return the pixel format. */ display_format get_format() const noexcept; /** * Sets the pixel format. * * \param df the pixel format. */ void set_format(display_format df) noexcept; /** * Gets the refresh rate in Hz. * * \return the refresh rate in Hz. */ uint get_refresh_rate() const noexcept; /** * Sets the refresh rate in Hz. * * \param refresh_rate the refresh rate in Hz. */ void set_refresh_rate(uint refresh_rate) noexcept; private: vec2u m_size; display_format m_format; uint m_refresh_rate; }; /** * Checks if two display_mode objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator==( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if two display_mode objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator!=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is less than rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator<( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is greater than rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator>( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is less or equal to rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator<=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Checks if lhs is greater or equal to rhs. * * \param lhs the left operand. * * \param rhs the right operand. * * \return the result of the check. */ HOU_SYS_API bool operator>=( const display_mode& lhs, const display_mode& rhs) noexcept; /** * Writes a display_mode object into a stream. * * \param os the stream. * * \param vm the display_mode object. * * \return a reference to the stream. */ HOU_SYS_API std::ostream& operator<<(std::ostream& os, const display_mode& vm); namespace prv { /** * Converts an SDL_DisplayMode object into a display_mode object. * * \param mode_in the input object. * * \return the converted object. */ display_mode convert(const SDL_DisplayMode& mode_in); /** * Converts ad display_mode object into an SDL_DisplayMode object. * * \param mode_in the input object. * * \return the converted object. */ SDL_DisplayMode convert(const display_mode& mode_in); } // namespace prv } // namespace hou #endif
19.029557
81
0.676676
DavideCorradiDev
221d6faa32e8595da0b1bd6ff086a65a8110a646
3,555
cpp
C++
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
2
2016-12-03T22:09:50.000Z
2021-08-31T12:44:24.000Z
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
null
null
null
tests/test-hdr/ordered_list/hdr_lazy_kv_rcu_shb.cpp
TatyanaBerlenko/libcds
3f4dfab2aea72d70ce44e7fbc02da9a6908f0781
[ "BSD-2-Clause" ]
2
2018-05-26T19:27:12.000Z
2021-08-31T12:44:28.000Z
//$$CDS-header$$ #include "ordered_list/hdr_lazy_kv.h" #include <cds/urcu/signal_buffered.h> #include <cds/container/lazy_kvlist_rcu.h> namespace ordlist { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { typedef cds::urcu::gc< cds::urcu::signal_buffered<> > rcu_type; struct RCU_SHB_cmp_traits : public cc::lazy_list::traits { typedef LazyKVListTestHeader::cmp<LazyKVListTestHeader::key_type> compare; }; } #endif void LazyKVListTestHeader::RCU_SHB_cmp() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_cmp_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::compare< cmp<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_less_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; }; } #endif void LazyKVListTestHeader::RCU_SHB_less() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_less_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::less< lt<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_cmpmix_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::cmp<LazyKVListTestHeader::key_type> compare; typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; }; } #endif void LazyKVListTestHeader::RCU_SHB_cmpmix() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_cmpmix_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::compare< cmp<key_type> > ,cc::opt::less< lt<key_type> > >::type > opt_list; test_rcu< opt_list >(); #endif } #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED namespace { struct RCU_SHB_ic_traits: public cc::lazy_list::traits { typedef LazyKVListTestHeader::lt<LazyKVListTestHeader::key_type> less; typedef cds::atomicity::item_counter item_counter; }; } #endif void LazyKVListTestHeader::RCU_SHB_ic() { #ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED // traits-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, RCU_SHB_ic_traits > list; test_rcu< list >(); // option-based version typedef cc::LazyKVList< rcu_type, key_type, value_type, cc::lazy_list::make_traits< cc::opt::less< lt<key_type> > ,cc::opt::item_counter< cds::atomicity::item_counter > >::type > opt_list; test_rcu< opt_list >(); #endif } } // namespace ordlist
28.902439
93
0.627848
TatyanaBerlenko
2221d8c3f785527fe82e4b088a483f0a12017919
7,967
cc
C++
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
5
2015-09-16T06:10:59.000Z
2019-12-25T05:30:00.000Z
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
null
null
null
talk/p2p/base/p2ptransport.cc
udit043/libjingle
dd7c03d0c5c358ada97feae44a5f76acad8dca13
[ "BSD-3-Clause" ]
3
2015-08-01T11:38:08.000Z
2019-11-01T05:16:09.000Z
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/p2p/base/p2ptransport.h" #include "talk/base/common.h" #include "talk/p2p/base/candidate.h" #include "talk/p2p/base/constants.h" #include "talk/base/helpers.h" #include "talk/p2p/base/p2ptransportchannel.h" #include "talk/p2p/base/sessionmanager.h" #include "talk/xmllite/qname.h" #include "talk/xmllite/xmlelement.h" #include "talk/xmpp/constants.h" namespace { // We only allow usernames to be this many characters or fewer. const size_t kMaxUsernameSize = 16; } // namespace namespace cricket { const std::string kNsP2pTransport("http://www.google.com/transport/p2p"); const buzz::QName kQnP2pTransport(true, kNsP2pTransport, "transport"); const buzz::QName kQnP2pCandidate(true, kNsP2pTransport, "candidate"); const buzz::QName kQnP2pUnknownChannelName(true, kNsP2pTransport, "unknown-channel-name"); P2PTransport::P2PTransport(SessionManager* session_manager) : Transport(session_manager, kNsP2pTransport) { } P2PTransport::~P2PTransport() { DestroyAllChannels(); } buzz::XmlElement* P2PTransport::CreateTransportOffer() { return new buzz::XmlElement(kQnP2pTransport, true); } buzz::XmlElement* P2PTransport::CreateTransportAnswer() { return new buzz::XmlElement(kQnP2pTransport, true); } bool P2PTransport::OnTransportOffer(const buzz::XmlElement* elem) { ASSERT(elem->Name() == kQnP2pTransport); // We don't support any options, so we ignore them. return true; } bool P2PTransport::OnTransportAnswer(const buzz::XmlElement* elem) { ASSERT(elem->Name() == kQnP2pTransport); // We don't support any options. We fail if any are given. The other side // should know from our request that we expected an empty response. return elem->FirstChild() == NULL; } bool P2PTransport::OnTransportMessage(const buzz::XmlElement* msg, const buzz::XmlElement* stanza) { ASSERT(msg->Name() == kQnP2pTransport); for (const buzz::XmlElement* elem = msg->FirstElement(); elem != NULL; elem = elem->NextElement()) { if (elem->Name() == kQnP2pCandidate) { // Make sure this candidate is valid. Candidate candidate; if (!ParseCandidate(stanza, elem, &candidate)) return false; ForwardChannelMessage(elem->Attr(buzz::QN_NAME), new buzz::XmlElement(*elem)); } } return true; } bool P2PTransport::OnTransportError(const buzz::XmlElement* session_msg, const buzz::XmlElement* error) { ASSERT(error->Name().Namespace() == kNsP2pTransport); if ((error->Name() == kQnP2pUnknownChannelName) && error->HasAttr(buzz::QN_NAME)) { std::string channel_name = error->Attr(buzz::QN_NAME); if (HasChannel(channel_name)) { SignalChannelGone(this, channel_name); } } return true; } void P2PTransport::OnTransportChannelMessages( const std::vector<buzz::XmlElement*>& candidates) { buzz::XmlElement* transport = new buzz::XmlElement(kQnP2pTransport, true); for (size_t i = 0; i < candidates.size(); ++i) transport->AddElement(candidates[i]); std::vector<buzz::XmlElement*> elems; elems.push_back(transport); SignalTransportMessage(this, elems); } bool P2PTransport::ParseCandidate(const buzz::XmlElement* stanza, const buzz::XmlElement* elem, Candidate* candidate) { // Check for all of the required attributes. if (!elem->HasAttr(buzz::QN_NAME) || !elem->HasAttr(QN_ADDRESS) || !elem->HasAttr(QN_PORT) || !elem->HasAttr(QN_USERNAME) || !elem->HasAttr(QN_PREFERENCE) || !elem->HasAttr(QN_PROTOCOL) || !elem->HasAttr(QN_GENERATION)) { return BadRequest(stanza, "candidate missing required attribute", NULL); } // Make sure the channel named actually exists. if (!HasChannel(elem->Attr(buzz::QN_NAME))) { scoped_ptr<buzz::XmlElement> extra_info(new buzz::XmlElement(kQnP2pUnknownChannelName)); extra_info->AddAttr(buzz::QN_NAME, elem->Attr(buzz::QN_NAME)); return BadRequest(stanza, "channel named in candidate does not exist", extra_info.get()); } // Parse the address given. talk_base::SocketAddress address; if (!ParseAddress(stanza, elem, &address)) return false; candidate->set_name(elem->Attr(buzz::QN_NAME)); candidate->set_address(address); candidate->set_username(elem->Attr(QN_USERNAME)); candidate->set_preference_str(elem->Attr(QN_PREFERENCE)); candidate->set_protocol(elem->Attr(QN_PROTOCOL)); candidate->set_generation_str(elem->Attr(QN_GENERATION)); // Check that the username is not too long and does not use any bad chars. if (candidate->username().size() > kMaxUsernameSize) return BadRequest(stanza, "candidate username is too long", NULL); if (!IsBase64Encoded(candidate->username())) return BadRequest(stanza, "candidate username has non-base64 encoded characters", NULL); // Look for the non-required attributes. if (elem->HasAttr(QN_PASSWORD)) candidate->set_password(elem->Attr(QN_PASSWORD)); if (elem->HasAttr(buzz::QN_TYPE)) candidate->set_type(elem->Attr(buzz::QN_TYPE)); if (elem->HasAttr(QN_NETWORK)) candidate->set_network_name(elem->Attr(QN_NETWORK)); return true; } buzz::XmlElement* P2PTransport::TranslateCandidate(const Candidate& c) { buzz::XmlElement* candidate = new buzz::XmlElement(kQnP2pCandidate); candidate->SetAttr(buzz::QN_NAME, c.name()); candidate->SetAttr(QN_ADDRESS, c.address().IPAsString()); candidate->SetAttr(QN_PORT, c.address().PortAsString()); candidate->SetAttr(QN_PREFERENCE, c.preference_str()); candidate->SetAttr(QN_USERNAME, c.username()); candidate->SetAttr(QN_PROTOCOL, c.protocol()); candidate->SetAttr(QN_GENERATION, c.generation_str()); if (c.password().size() > 0) candidate->SetAttr(QN_PASSWORD, c.password()); if (c.type().size() > 0) candidate->SetAttr(buzz::QN_TYPE, c.type()); if (c.network_name().size() > 0) candidate->SetAttr(QN_NETWORK, c.network_name()); return candidate; } TransportChannelImpl* P2PTransport::CreateTransportChannel( const std::string& name, const std::string &session_type) { return new P2PTransportChannel( name, session_type, this, session_manager()->port_allocator()); } void P2PTransport::DestroyTransportChannel(TransportChannelImpl* channel) { delete channel; } } // namespace cricket
37.938095
80
0.702648
udit043
22283dbfb773142e676b11005e62a63f25061cbf
4,747
cpp
C++
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
check/core/matrix/dense/dense_matrix/test/get_col_segment.cpp
emfomy/mcnla
9f9717f4d6449bbd467c186651856d6212035667
[ "MIT" ]
null
null
null
#include "../test.hpp" #include <queue> TYPED_TEST(DenseMatrixTest_ColMajor_Size8x5_Pitch8, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), 1); EXPECT_TRUE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0 + colidx*pitch)); EXPECT_EQ(segment.offset(), offset + row0 + colidx*pitch); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0) + colidx*pitch]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0) + colidx*pitch]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_ColMajor_Size8x5_Pitch10, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), 1); EXPECT_TRUE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0 + colidx*pitch)); EXPECT_EQ(segment.offset(), offset + row0 + colidx*pitch); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0) + colidx*pitch]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0) + colidx*pitch]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_RowMajor_Size8x5_Pitch5, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), pitch); EXPECT_FALSE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0*pitch + colidx)); EXPECT_EQ(segment.offset(), offset + row0*pitch + colidx); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0)*pitch + colidx]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0)*pitch + colidx]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); } TYPED_TEST(DenseMatrixTest_RowMajor_Size8x5_Pitch10, GetColSegment) { const auto pitch = this->pitch_; const auto capacity = this->capacity_; const auto offset = this->offset_; const auto mat = this->mat_; const auto valptr0 = this->valptr0_; const mcnla::index_t colidx = 2; const mcnla::index_t row0 = 3, rows = 5; auto segment = mat({row0, row0+rows}, colidx); EXPECT_EQ(segment.len(), rows); EXPECT_EQ(segment.nelem(), rows); EXPECT_EQ(segment.stride(), pitch); EXPECT_FALSE(segment.isShrunk()); EXPECT_EQ(segment.capacity(), capacity - (row0*pitch + colidx)); EXPECT_EQ(segment.offset(), offset + row0*pitch + colidx); EXPECT_EQ(segment.valPtr(), &(mat(row0, colidx))); for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), mat(i+row0, colidx)); } for ( auto i = 0; i < rows; ++i ) { EXPECT_EQ(segment(i), valptr0[offset + (i+row0)*pitch + colidx]); } std::queue<TypeParam> tmp; for ( auto i = 0; i < rows; ++i ) { tmp.push(valptr0[offset + (i+row0)*pitch + colidx]); } for ( auto value : segment ) { EXPECT_EQ(value, tmp.front()); tmp.pop(); } EXPECT_EQ(tmp.size(), 0); }
27.281609
69
0.629029
emfomy
2232c20a6c1a4c2a04f3a89074d07b5007312040
2,608
cpp
C++
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
storage/src/Storage.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
#include "storage/Storage.h" #include <yaml-cpp/yaml.h> #include <filesystem> #include <fstream> #include <string> namespace storage::key { const std::string row = "row"; const std::string col = "col"; const std::string pos = "pos"; const std::string value = "value"; } // namespace storage::key namespace YAML { template <> struct convert<common::Position> { static Node encode(const common::Position& pos) { Node node; node[storage::key::row] = pos.row; node[storage::key::col] = pos.col; return node; } static bool decode(const Node& node, common::Position& pos) { pos.row = node[storage::key::row].as<common::Index>(); pos.col = node[storage::key::col].as<common::Index>(); return true; } }; template <> struct convert<common::NewAction> { static Node encode(const common::NewAction& action) { Node node; node[storage::key::pos] = action.pos; node[storage::key::value] = action.value; return node; } static bool decode(const Node& node, common::NewAction& action) { action.pos = node[storage::key::pos].as<common::Position>(); action.value = node[storage::key::value].as<common::Value>(); return true; } }; } // namespace YAML namespace storage { const std::string fileName = "game.yaml"; namespace key { const std::string bestScore = "bestScore"; const std::string score = "score"; const std::string isGameOver = "isGameOver"; const std::string rows = "rows"; const std::string cols = "cols"; const std::string newActions = "newActions"; } // namespace key use_case_interface::GameData Storage::loadGame() { try { YAML::Node node = YAML::LoadFile(fileName); use_case_interface::GameData gameData; gameData.bestScore = node[key::bestScore].as<int>(); gameData.score = node[key::score].as<int>(); gameData.isGameOver = node[key::isGameOver].as<bool>(); gameData.rows = node[key::rows].as<common::Index>(); gameData.cols = node[key::cols].as<common::Index>(); gameData.newActions = node[key::newActions].as<common::NewActions>(); return gameData; } catch (const std::exception& e) { return {}; } } void Storage::saveGame(const use_case_interface::GameData& gameData) { YAML::Node node; node[key::bestScore] = gameData.bestScore; node[key::score] = gameData.score; node[key::isGameOver] = gameData.isGameOver; node[key::rows] = gameData.rows; node[key::cols] = gameData.cols; node[key::newActions] = gameData.newActions; std::ofstream ofs{fileName}; ofs << node; } void Storage::clear() { std::filesystem::remove(fileName); } } // namespace storage
26.612245
73
0.671779
codingpotato
2239226ca034a82757bfc7fe66f872245acb1fd5
631
cpp
C++
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
71
2015-01-17T12:35:43.000Z
2021-12-01T06:04:22.000Z
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
33
2015-02-24T00:21:53.000Z
2018-01-18T01:12:23.000Z
src/Callback-v11.cpp
Alfheim/node-julia
72c202e149912ba09d3aea8c006aba83ae447b64
[ "MIT" ]
15
2015-04-24T06:48:03.000Z
2021-12-07T20:39:38.000Z
#include <node_version.h> #include "Callback.h" using namespace v8; nj::Callback::Callback(const Local<Function> &cb,const Local<Object> &recv):callback_persist(),recv_persist() { Isolate *I = Isolate::GetCurrent(); callback_persist.Reset(I,cb); recv_persist.Reset(I,recv); } Local<Function> nj::Callback::cb() { Isolate *I = Isolate::GetCurrent(); return Local<Function>::New(I,callback_persist); } Local<Object> nj::Callback::recv() { Isolate *I = Isolate::GetCurrent(); return Local<Object>::New(I,recv_persist); } nj::Callback::~Callback() { callback_persist.Reset(); recv_persist.Reset(); }
19.121212
109
0.692552
Alfheim
223b72eb05b17f7e523649297589f8da0aa2f026
3,041
cpp
C++
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/Battle_ProcDead_APet.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include "stdhdrs.h" #include "Server.h" #include "Battle.h" #include "WarCastle.h" #include "CmdMsg.h" #include "Exp.h" #include "Log.h" #include "doFunc.h" void ProcDead(CAPet* df, CCharacter* of) { CPC* opc = NULL; CNPC* onpc = NULL; CPet* opet = NULL; CElemental* oelemental = NULL; CAPet* oapet = NULL; if( IS_NPC(of) && TO_NPC(of)->Check_MobFlag(STATE_MONSTER_MERCENARY) && TO_NPC(of)->GetOwner() ) { TO_NPC(of)->GetOwner()->SetSummonOwners_target(NULL); } switch (of->m_type) { case MSG_CHAR_PC: opc = TO_PC(of); break; case MSG_CHAR_NPC: onpc = TO_NPC(of); break; case MSG_CHAR_PET: opet = TO_PET(of); opc = opet->GetOwner(); break; case MSG_CHAR_ELEMENTAL: oelemental = TO_ELEMENTAL(of); opc = oelemental->GetOwner(); break; case MSG_CHAR_APET: oapet = TO_APET( of ); opc = oapet->GetOwner(); break; default: return ; } if( opc ) opc->SetSummonOwners_target(NULL); bool bPKPenalty = false; if (df->GetOwner()) { bPKPenalty = (opc) ? IsPK(opc, df) : false; if (bPKPenalty) CalcPKPoint(opc, df->GetOwner(), true); } if( !bPKPenalty && !(df->GetOwner()->GetMapAttr() & MATT_FREEPKZONE) ) { if( df->m_level >= 10 ) { df->m_exp = (LONGLONG) ( df->m_exp - ( df->GetNeedExp() * 0.02) ) ; if( df->m_exp < 0 ) df->m_exp=0; } df->AddFaith(-10); } DelAttackList(df); CPC* owner = df->GetOwner(); const char* ownerName = "NO OWNER"; const char* ownerNick = "NO OWNER"; const char* ownerID = "NO OWNER"; if (owner) { ownerNick = (owner->IsNick()) ? owner->GetName() : ownerNick; ownerName = owner->m_name; ownerID = owner->m_desc->m_idname; } // TODO : petlog GAMELOG << init("PET DEAD") << "APET" << delim << "INDEX" << delim << df->m_index << delim << "LEVEL" << delim << df->m_level << delim << "OWNER" << delim << ownerName << delim << ownerNick << delim << ownerID << delim << "ATTACKER" << delim << "TYPE" << delim; switch (of->m_type) { case MSG_CHAR_NPC: GAMELOG << "NPC" << delim << onpc->m_name << end; break; case MSG_CHAR_PC: case MSG_CHAR_PET: case MSG_CHAR_ELEMENTAL: case MSG_CHAR_APET: default: if (opc) { GAMELOG << "PC" << delim << opc->m_index << delim << opc->GetName() << end; } else { GAMELOG << "UNKNOWN" << delim << of->m_index << delim << of->m_name << end; } break; } if (owner) { // Item şŔŔÎ CItem* apet_item = owner->m_wearInventory.wearItemInfo[WEARING_PET]; if( !apet_item ) return; apet_item->setFlag(apet_item->getFlag() | FLAG_ITEM_SEALED); { owner->m_wearInventory.sendOneItemInfo(WEARING_PET); } df->m_bMount = false; // Á׾úŔ»¶§´Â ÂřżëÇŘÁ¦żˇĽ­ Disappear ¸¦ ş¸ł»Áö ľĘ±â¶«ą®żˇ ż©±âĽ­ ĽżżˇĽ­ »©ÁŘ´Ů. df->m_bSummon = false; DelAttackList(df); if( df->m_pZone && df->m_pArea ) df->m_pArea->CharFromCell(df, true); { // Ćę »óĹ ş¸łż CNetMsg::SP rmsg(new CNetMsg); ExAPetStatusMsg(rmsg, df); SEND_Q(rmsg, owner->m_desc); } } }
19.125786
97
0.604078
openlastchaos
2241d810412d9325c504a0a757283b15dcae67c9
3,000
cpp
C++
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
src/verify/main_verify.cpp
velidurmuscan/VDSProject_Group6
74ad2e315ffe271a66d744078bc16fe002d33874
[ "Unlicense", "MIT" ]
null
null
null
/*============================================================================= Written by Mohammad R Fadiheh (2017) =============================================================================*/ #include<iostream> #include<fstream> #include<string> #include<sstream> #include<map> struct node { std::string var_name; int low; int high; }; typedef std::map<int, node> uniqueTable; bool isEquivalent(uniqueTable BDD1, uniqueTable BDD2, int root1, int root2) { if(BDD1.find(root1) == BDD1.end() || BDD2.find(root2) == BDD2.end()) return false; if(root1 == 1 && root2 == 1) return true; if(root1 == 0 && root2 == 0) return true; if(root1 != root2 && ( (root1 == 0 || root1 == 1) || (root2 == 0 || root2 == 1) ) ) return false; if(BDD1[root1].var_name != BDD2[root2].var_name) return false; return isEquivalent(BDD1, BDD2, BDD1[root1].low, BDD2[root2].low) and isEquivalent(BDD1, BDD2, BDD1[root1].high, BDD2[root2].high); } int main(int argc, char* argv[]) { /* Number of arguments validation */ if (3 > argc) { std::cout << "Must specify a filename!" << std::endl; return -1; } uniqueTable BDD1, BDD2; std::string BDD1_file = argv[1]; std::string BDD2_file = argv[2]; std::ifstream BDD1_if(BDD1_file.c_str()); std::ifstream BDD2_if(BDD2_file.c_str()); if(!BDD1_if.is_open() || !BDD2_if.is_open()) { std::cout << "invalid file!" << std::endl; return -1; } std::stringstream ss; std::string temp; std::string var_name; int id, top_var; while(!BDD1_if.eof()) { node n; temp.clear(); std::getline(BDD1_if, temp,'\n'); if(temp.find("Terminal Node: 1") != std::string::npos) { n.var_name = ""; n.low = 1; n.high = 1; BDD1.insert(std::pair<int,node>(1,n)); } else if(temp.find("Terminal Node: 0") != std::string::npos) { n.var_name = ""; n.low = 0; n.high = 0; BDD1.insert(std::pair<int,node>(0,n)); } else if(temp.find("Variable Node:") != std::string::npos) { ss.clear(); ss.str(temp); ss>>temp>>temp>>id>>temp>>temp>>temp>>top_var>>temp>>temp>>temp>>n.var_name>>temp>>n.low>>temp>>n.high; BDD1.insert(std::pair<int,node>(id,n)); } } while(!BDD2_if.eof()) { node n; temp.clear(); std::getline(BDD2_if, temp,'\n'); if(temp.find("Terminal Node: 1") != std::string::npos) { n.var_name = ""; n.low = 1; n.high = 1; BDD2.insert(std::pair<int,node>(1,n)); } else if(temp.find("Terminal Node: 0") != std::string::npos) { n.var_name = ""; n.low = 0; n.high = 0; BDD2.insert(std::pair<int,node>(0,n)); } else if(temp.find("Variable Node:") != std::string::npos) { ss.clear(); ss.str(temp); ss>>temp>>temp>>id>>temp>>temp>>temp>>top_var>>temp>>temp>>temp>>n.var_name>>temp>>n.low>>temp>>n.high; BDD2.insert(std::pair<int,node>(id,n)); } } if( isEquivalent(BDD1, BDD2, BDD1.rbegin()->first, BDD2.rbegin()->first) ) std::cout<<"Equivalent!"<<std::endl; else std::cout<<"Not Equivalent!"<<std::endl; return 0; }
22.900763
132
0.574333
velidurmuscan
22479d2daedc168c0f739920d2e729da195d6ce8
189
hpp
C++
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
src/components/allcomponents.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
null
null
null
#ifndef INCLUDE_BALLCOMPONENTS #define INCLUDE_BALLCOMPONENTS #include "../components.hpp" #include "primitives.hpp" #include "drawingcomponents.hpp" #include "gamecomponents.hpp" #endif
18.9
32
0.804233
wareya
22481376becb28333dc86377cfd200f030a63ac2
14,430
cpp
C++
OREData/ored/marketdata/inflationcurve.cpp
nvolfango/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
1
2021-03-30T17:24:17.000Z
2021-03-30T17:24:17.000Z
OREData/ored/marketdata/inflationcurve.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
OREData/ored/marketdata/inflationcurve.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ored/marketdata/inflationcurve.hpp> #include <ored/utilities/log.hpp> #include <qle/indexes/inflationindexwrapper.hpp> #include <ql/cashflows/couponpricer.hpp> #include <ql/cashflows/yoyinflationcoupon.hpp> #include <ql/pricingengines/swap/discountingswapengine.hpp> #include <ql/termstructures/inflation/piecewiseyoyinflationcurve.hpp> #include <ql/termstructures/inflation/piecewisezeroinflationcurve.hpp> #include <ql/time/daycounters/actual365fixed.hpp> #include <algorithm> using namespace QuantLib; using namespace std; using namespace ore::data; namespace ore { namespace data { InflationCurve::InflationCurve(Date asof, InflationCurveSpec spec, const Loader& loader, const CurveConfigurations& curveConfigs, const Conventions& conventions, map<string, boost::shared_ptr<YieldCurve>>& yieldCurves) { try { const boost::shared_ptr<InflationCurveConfig>& config = curveConfigs.inflationCurveConfig(spec.curveConfigID()); boost::shared_ptr<InflationSwapConvention> conv = boost::dynamic_pointer_cast<InflationSwapConvention>(conventions.get(config->conventions())); QL_REQUIRE(conv != nullptr, "convention " << config->conventions() << " could not be found."); Handle<YieldTermStructure> nominalTs; auto it = yieldCurves.find(config->nominalTermStructure()); if (it != yieldCurves.end()) { nominalTs = it->second->handle(); } else { QL_FAIL("The nominal term structure, " << config->nominalTermStructure() << ", required in the building " "of the curve, " << spec.name() << ", was not found."); } // We loop over all market data, looking for quotes that match the configuration const std::vector<string> strQuotes = config->swapQuotes(); std::vector<Handle<Quote>> quotes(strQuotes.size(), Handle<Quote>()); std::vector<Period> terms(strQuotes.size()); std::vector<bool> isZc(strQuotes.size(), true); for (auto& md : loader.loadQuotes(asof)) { if (md->asofDate() == asof && (md->instrumentType() == MarketDatum::InstrumentType::ZC_INFLATIONSWAP || (md->instrumentType() == MarketDatum::InstrumentType::YY_INFLATIONSWAP && config->type() == InflationCurveConfig::Type::YY))) { boost::shared_ptr<ZcInflationSwapQuote> q = boost::dynamic_pointer_cast<ZcInflationSwapQuote>(md); if (q != NULL && q->index() == spec.index()) { auto it = std::find(strQuotes.begin(), strQuotes.end(), q->name()); if (it != strQuotes.end()) { QL_REQUIRE(quotes[it - strQuotes.begin()].empty(), "duplicate quote " << q->name()); quotes[it - strQuotes.begin()] = q->quote(); terms[it - strQuotes.begin()] = q->term(); isZc[it - strQuotes.begin()] = true; } } boost::shared_ptr<YoYInflationSwapQuote> q2 = boost::dynamic_pointer_cast<YoYInflationSwapQuote>(md); if (q2 != NULL && q2->index() == spec.index()) { auto it = std::find(strQuotes.begin(), strQuotes.end(), q2->name()); if (it != strQuotes.end()) { QL_REQUIRE(quotes[it - strQuotes.begin()].empty(), "duplicate quote " << q2->name()); quotes[it - strQuotes.begin()] = q2->quote(); terms[it - strQuotes.begin()] = q2->term(); isZc[it - strQuotes.begin()] = false; } } } } // do we have all quotes and do we derive yoy quotes from zc ? for (Size i = 0; i < strQuotes.size(); ++i) { QL_REQUIRE(!quotes[i].empty(), "quote " << strQuotes[i] << " not found in market data."); QL_REQUIRE(isZc[i] == isZc[0], "mixed zc and yoy quotes"); } bool derive_yoy_from_zc = (config->type() == InflationCurveConfig::Type::YY && isZc[0]); // construct seasonality boost::shared_ptr<Seasonality> seasonality; if (config->seasonalityBaseDate() != Null<Date>()) { std::vector<string> strFactorIDs = config->seasonalityFactors(); std::vector<double> factors(strFactorIDs.size()); for (Size i = 0; i < strFactorIDs.size(); i++) { boost::shared_ptr<MarketDatum> marketQuote = loader.get(strFactorIDs[i], asof); // Check that we have a valid seasonality factor if (marketQuote) { QL_REQUIRE(marketQuote->instrumentType() == MarketDatum::InstrumentType::SEASONALITY, "Market quote (" << marketQuote->name() << ") not of type seasonality."); // Currently only monthly seasonality with 12 multiplicative factors os allowed QL_REQUIRE(config->seasonalityFrequency() == Monthly && strFactorIDs.size() == 12, "Only monthly seasonality with 12 factors is allowed. Provided " << config->seasonalityFrequency() << " with " << strFactorIDs.size() << " factors."); boost::shared_ptr<SeasonalityQuote> sq = boost::dynamic_pointer_cast<SeasonalityQuote>(marketQuote); QL_REQUIRE(sq->type() == "MULT", "Market quote (" << sq->name() << ") not of multiplicative type."); Size seasBaseDateMonth = ((Size)config->seasonalityBaseDate().month()); int findex = sq->applyMonth() - seasBaseDateMonth; if (findex < 0) findex += 12; QL_REQUIRE(findex >= 0 && findex < 12, "Unexpected seasonality index " << findex); factors[findex] = sq->quote()->value(); } else { QL_FAIL("Could not find quote for ID " << strFactorIDs[i] << " with as of date " << io::iso_date(asof) << "."); } } QL_REQUIRE(!factors.empty(), "no seasonality factors found"); seasonality = boost::make_shared<MultiplicativePriceSeasonality>(config->seasonalityBaseDate(), config->seasonalityFrequency(), factors); } // construct curve (ZC or YY depending on configuration) // base zero / yoy rate: if given, take it, otherwise set it to first quote Real baseRate = config->baseRate() != Null<Real>() ? config->baseRate() : quotes[0]->value(); interpolatedIndex_ = conv->interpolated(); boost::shared_ptr<YoYInflationIndex> zc_to_yoy_conversion_index; if (config->type() == InflationCurveConfig::Type::ZC || derive_yoy_from_zc) { // ZC Curve std::vector<boost::shared_ptr<ZeroInflationTraits::helper>> instruments; boost::shared_ptr<ZeroInflationIndex> index = conv->index(); for (Size i = 0; i < strQuotes.size(); ++i) { // QL conventions do not incorporate settlement delay => patch here once QL is patched Date maturity = asof + terms[i]; boost::shared_ptr<ZeroInflationTraits::helper> instrument = boost::make_shared<ZeroCouponInflationSwapHelper>(quotes[i], conv->observationLag(), maturity, conv->fixCalendar(), conv->fixConvention(), conv->dayCounter(), index, nominalTs); // The instrument gets registered to update on change of evaluation date. This triggers a // rebootstrapping of the curve. In order to avoid this during simulation we unregister from the // evaluationDate. instrument->unregisterWith(Settings::instance().evaluationDate()); instruments.push_back(instrument); } curve_ = boost::shared_ptr<PiecewiseZeroInflationCurve<Linear>>(new PiecewiseZeroInflationCurve<Linear>( asof, config->calendar(), config->dayCounter(), config->lag(), config->frequency(), interpolatedIndex_, baseRate, nominalTs, instruments, config->tolerance())); // force bootstrap so that errors are thrown during the build, not later boost::static_pointer_cast<PiecewiseZeroInflationCurve<Linear>>(curve_)->zeroRate(QL_EPSILON); if (derive_yoy_from_zc) { // set up yoy wrapper with empty ts, so that zero index is used to forecast fixings // for this link the appropriate curve to the zero index zc_to_yoy_conversion_index = boost::make_shared<QuantExt::YoYInflationIndexWrapper>( index->clone(Handle<ZeroInflationTermStructure>( boost::dynamic_pointer_cast<ZeroInflationTermStructure>(curve_))), interpolatedIndex_); } } if (config->type() == InflationCurveConfig::Type::YY) { // YOY Curve std::vector<boost::shared_ptr<YoYInflationTraits::helper>> instruments; boost::shared_ptr<ZeroInflationIndex> zcindex = conv->index(); boost::shared_ptr<YoYInflationIndex> index = boost::make_shared<QuantExt::YoYInflationIndexWrapper>(zcindex, interpolatedIndex_); boost::shared_ptr<InflationCouponPricer> yoyCpnPricer = boost::make_shared<QuantExt::YoYInflationCouponPricer2>(nominalTs); for (Size i = 0; i < strQuotes.size(); ++i) { Date maturity = asof + terms[i]; Real effectiveQuote = quotes[i]->value(); if (derive_yoy_from_zc) { // contruct a yoy swap just as it is done in the yoy inflation helper Schedule schedule = MakeSchedule() .from(Settings::instance().evaluationDate()) .to(maturity) .withTenor(1 * Years) .withConvention(Unadjusted) .withCalendar(conv->fixCalendar()) .backwards(); YearOnYearInflationSwap tmp(YearOnYearInflationSwap::Payer, 1000000.0, schedule, 0.02, conv->dayCounter(), schedule, zc_to_yoy_conversion_index, conv->observationLag(), 0.0, conv->dayCounter(), conv->fixCalendar(), conv->fixConvention()); for (auto& c : tmp.yoyLeg()) { auto cpn = boost::dynamic_pointer_cast<YoYInflationCoupon>(c); QL_REQUIRE(cpn, "yoy inflation coupon expected, could not cast"); cpn->setPricer(yoyCpnPricer); } boost::shared_ptr<PricingEngine> engine = boost::make_shared<QuantLib::DiscountingSwapEngine>(nominalTs); tmp.setPricingEngine(engine); effectiveQuote = tmp.fairRate(); DLOG("Derive " << terms[i] << " yoy quote " << effectiveQuote << " from zc quote " << quotes[i]->value()); } // QL conventions do not incorporate settlement delay => patch here once QL is patched boost::shared_ptr<YoYInflationTraits::helper> instrument = boost::make_shared<YearOnYearInflationSwapHelper>( Handle<Quote>(boost::make_shared<SimpleQuote>(effectiveQuote)), conv->observationLag(), maturity, conv->fixCalendar(), conv->fixConvention(), conv->dayCounter(), index, nominalTs); instrument->unregisterWith(Settings::instance().evaluationDate()); instruments.push_back(instrument); } // base zero rate: if given, take it, otherwise set it to first quote Real baseRate = config->baseRate() != Null<Real>() ? config->baseRate() : quotes[0]->value(); curve_ = boost::shared_ptr<PiecewiseYoYInflationCurve<Linear>>(new PiecewiseYoYInflationCurve<Linear>( asof, config->calendar(), config->dayCounter(), config->lag(), config->frequency(), interpolatedIndex_, baseRate, nominalTs, instruments, config->tolerance())); // force bootstrap so that errors are thrown during the build, not later boost::static_pointer_cast<PiecewiseYoYInflationCurve<Linear>>(curve_)->yoyRate(QL_EPSILON); } if (seasonality != nullptr) { curve_->setSeasonality(seasonality); } curve_->enableExtrapolation(config->extrapolate()); curve_->unregisterWith(Settings::instance().evaluationDate()); } catch (std::exception& e) { QL_FAIL("inflation curve building failed: " << e.what()); } catch (...) { QL_FAIL("inflation curve building failed: unknown error"); } } } // namespace data } // namespace ore
59.139344
120
0.570132
nvolfango
22493a49d2e35d060825b9b6db2a8badc554f516
7,609
cpp
C++
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
src/xtd.core.native.unix/src/xtd/native/unix/directory.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#define __XTD_CORE_NATIVE_LIBRARY__ #include <xtd/native/directory.h> #include <xtd/native/file_system.h> #undef __XTD_CORE_NATIVE_LIBRARY__ #include <dirent.h> #include <unistd.h> #include <sys/param.h> #include <sys/stat.h> using namespace std; using namespace xtd::native; namespace { bool pattern_compare(const string& file_name, const string& pattern) { if (pattern.empty()) return file_name.empty(); if (file_name.empty()) return false; if (pattern == "*" || pattern == "*.*") return true; if (pattern[0] == '*') return pattern_compare(file_name, pattern.substr(1)) || pattern_compare(file_name.substr(1), pattern); return ((pattern[0] == '?') || (file_name[0] == pattern[0])) && pattern_compare(file_name.substr(1), pattern.substr(1)); } } struct directory::directory_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::directory_iterator::directory_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::directory_iterator::directory_iterator() { data_ = make_shared<data>(); } directory::directory_iterator::~directory_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::directory_iterator& directory::directory_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY || string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::directory_iterator directory::directory_iterator::operator++(int) { directory_iterator result = *this; ++(*this); return result; } bool directory::directory_iterator::operator==(directory::directory_iterator other) const { return data_->current_ == other.data_->current_; } directory::directory_iterator::value_type directory::directory_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } struct directory::file_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::file_iterator::file_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::file_iterator::file_iterator() { data_ = make_shared<data>(); } directory::file_iterator::~file_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::file_iterator& directory::file_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY || string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::file_iterator directory::file_iterator::operator++(int) { file_iterator result = *this; ++(*this); return result; } bool directory::file_iterator::operator==(directory::file_iterator other) const { return data_->current_ == other.data_->current_; } directory::file_iterator::value_type directory::file_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } struct directory::file_and_directory_iterator::data { data() = default; data(const std::string& path, const std::string& pattern) : path_(path), pattern_(pattern) {} std::string path_; std::string pattern_; DIR* handle_ = nullptr; mutable string current_; }; directory::file_and_directory_iterator::file_and_directory_iterator(const std::string& path, const std::string& pattern) { data_ = make_shared<data>(path, pattern); data_->handle_ = opendir(data_->path_.c_str()); ++(*this); } directory::file_and_directory_iterator::file_and_directory_iterator() { data_ = make_shared<data>(); } directory::file_and_directory_iterator::~file_and_directory_iterator() { if (data_.use_count() == 1 && data_->handle_) { closedir(data_->handle_); data_->handle_ = nullptr; } } directory::file_and_directory_iterator& directory::file_and_directory_iterator::operator++() { dirent* item; int32_t attributes; do { if ((item = readdir(data_->handle_)) != nullptr) native::file_system::get_attributes(data_->path_ + '/' + item->d_name, attributes); } while (item != nullptr && (string(item->d_name) == "." || string(item->d_name) == ".." || !pattern_compare(item->d_name, data_->pattern_))); if (item == nullptr) data_->current_ = ""; else data_->current_ = data_->path_ + (data_->path_.rfind('/') == data_->path_.size() - 1 ? "" : "/") + item->d_name; return *this; } directory::file_and_directory_iterator directory::file_and_directory_iterator::operator++(int) { file_and_directory_iterator result = *this; ++(*this); return result; } bool directory::file_and_directory_iterator::operator==(directory::file_and_directory_iterator other) const { return data_->current_ == other.data_->current_; } directory::file_and_directory_iterator::value_type directory::file_and_directory_iterator::operator*() const { if (data_ == nullptr) return ""; return data_->current_; } int32_t directory::create(const std::string& directory_name) { return mkdir(directory_name.c_str(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH); } directory::directory_iterator directory::enumerate_directories(const std::string& path, const std::string& pattern) { return directory_iterator(path, pattern); } directory::file_iterator directory::enumerate_files(const std::string& path, const std::string& pattern) { return file_iterator(path, pattern); } directory::file_and_directory_iterator directory::enumerate_files_and_directories(const std::string& path, const std::string& pattern) { return file_and_directory_iterator(path, pattern); } bool directory::exists(const std::string& path) { int32_t attributes = 0; return file_system::get_attributes(path, attributes) == 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; } string directory::get_current_directory() { char path[MAXPATHLEN + 1]; return getcwd(path, MAXPATHLEN) ? path : ""; } int32_t directory::remove(const std::string& directory_name) { return rmdir(directory_name.c_str()); } int32_t directory::set_current_directory(const std::string& directory_name) { return chdir(directory_name.c_str()); }
34.90367
217
0.705086
BaderEddineOuaich
224cacc2e25eeabbac146d8cba9489c2bb5fe900
20,449
cpp
C++
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
libs/hmtslam/src/CHMTSLAM_main.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ /** An implementation of Hybrid Metric Topological SLAM (HMT-SLAM). * * The main entry points for a user are pushAction() and pushObservations(). Several parameters can be modified * through m_options. * * The mathematical models of this approach have been reported in: * - Blanco J.L., Fernandez-Madrigal J.A., and Gonzalez J., * "Towards a Unified Bayesian Approach to Hybrid Metric-Topological SLAM", * in IEEE Transactions on Robotics (TRO), Vol. 24, No. 2, April 2008. * - ... * * More information in the wiki page: http://www.mrpt.org/HMT-SLAM * */ #include "hmtslam-precomp.h" // Precomp header #include <mrpt/utils/CFileStream.h> #include <mrpt/utils/CConfigFile.h> #include <mrpt/utils/stl_serialization.h> #include <mrpt/system/filesystem.h> #include <mrpt/synch/CCriticalSection.h> #include <mrpt/utils/CMemoryStream.h> #include <mrpt/system/os.h> using namespace mrpt::slam; using namespace mrpt::hmtslam; using namespace mrpt::utils; using namespace mrpt::synch; using namespace mrpt::obs; using namespace mrpt::maps; using namespace mrpt::opengl; using namespace std; IMPLEMENTS_SERIALIZABLE(CHMTSLAM, CSerializable,mrpt::hmtslam) // Initialization of static members: int64_t CHMTSLAM::m_nextAreaLabel = 0; TPoseID CHMTSLAM::m_nextPoseID = 0; THypothesisID CHMTSLAM::m_nextHypID = COMMON_TOPOLOG_HYP + 1; /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CHMTSLAM::CHMTSLAM( ) : m_inputQueue_cs("inputQueue_cs"), m_map_cs("map_cs"), m_LMHs_cs("LMHs_cs") // m_semaphoreInputQueueHasData (0 /*Init state*/ ,1 /*Max*/ ), // m_eventNewObservationInserted(0 /*Init state*/ ,10000 /*Max*/ ) { // Initialize data structures: // ---------------------------- m_terminateThreads = false; m_terminationFlag_LSLAM = m_terminationFlag_TBI = m_terminationFlag_3D_viewer = false; // Create threads: // ----------------------- m_hThread_LSLAM = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_LSLAM ); m_hThread_TBI = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_TBI ); m_hThread_3D_viewer = mrpt::system::createThreadFromObjectMethod( this, &CHMTSLAM::thread_3D_viewer ); // Other variables: m_LSLAM_method = NULL; // Register default LC detectors: // -------------------------------- registerLoopClosureDetector("gridmaps", & CTopLCDetector_GridMatching::createNewInstance ); registerLoopClosureDetector("fabmap", & CTopLCDetector_FabMap::createNewInstance ); // Prepare an empty map: initializeEmptyMap(); } /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CHMTSLAM::~CHMTSLAM() { // Signal to threads that we are closing: // ------------------------------------------- m_terminateThreads = true; // Wait for threads: // ---------------------------------- MRPT_LOG_DEBUG("[CHMTSLAM::destructor] Waiting for threads end...\n"); mrpt::system::joinThread( m_hThread_3D_viewer ); mrpt::system::joinThread( m_hThread_LSLAM ); mrpt::system::joinThread( m_hThread_TBI ); MRPT_LOG_DEBUG("[CHMTSLAM::destructor] All threads finished.\n"); // Save the resulting H.Map if logging // -------------------------------------- if (!m_options.LOG_OUTPUT_DIR.empty()) { try { /* // Update the last area(s) in the HMAP: updateHierarchicalMapFromRBPF(); // Save: os::sprintf(auxFil,1000,"%s/hierarchicalMap.hmap",m_options.logOutputDirectory.c_str()); CFileStream f(auxFil,fomWrite); f << m_knownAreas; */ } catch(std::exception &e) { MRPT_LOG_WARN(mrpt::format("Ignoring exception at ~CHMTSLAM():\n%s",e.what())); } catch(...) { MRPT_LOG_WARN("Ignoring untyped exception at ~CHMTSLAM()"); } } // Delete data structures: // ---------------------------------- clearInputQueue(); // Others: if (m_LSLAM_method) { delete m_LSLAM_method; m_LSLAM_method = NULL; } // Delete TLC-detectors { synch::CCriticalSectionLocker lock( &m_topLCdets_cs ); // Clear old list: for (std::deque<CTopLCDetectorBase*>::iterator it=m_topLCdets.begin();it!=m_topLCdets.end();++it) delete *it; m_topLCdets.clear(); } } /*--------------------------------------------------------------- clearInputQueue ---------------------------------------------------------------*/ void CHMTSLAM::clearInputQueue() { // Wait for critical section { CCriticalSectionLocker locker( &m_inputQueue_cs); while (!m_inputQueue.empty()) { //delete m_inputQueue.front(); m_inputQueue.pop(); }; } } /*--------------------------------------------------------------- pushAction ---------------------------------------------------------------*/ void CHMTSLAM::pushAction( const CActionCollectionPtr &acts ) { if (m_terminateThreads) { // Discard it: //delete acts; return; } { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( acts ); } } /*--------------------------------------------------------------- pushObservations ---------------------------------------------------------------*/ void CHMTSLAM::pushObservations( const CSensoryFramePtr &sf ) { if (m_terminateThreads) { // Discard it: //delete sf; return; } { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( sf ); } } /*--------------------------------------------------------------- pushObservation ---------------------------------------------------------------*/ void CHMTSLAM::pushObservation( const CObservationPtr &obs ) { if (m_terminateThreads) { // Discard it: //delete obs; return; } // Add a CSensoryFrame with the obs: CSensoryFramePtr sf = CSensoryFrame::Create(); sf->insert(obs); // memory will be freed when deleting the SF in other thread { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); m_inputQueue.push( sf ); } } /*--------------------------------------------------------------- loadOptions ---------------------------------------------------------------*/ void CHMTSLAM::loadOptions( const mrpt::utils::CConfigFileBase &cfg ) { m_options.loadFromConfigFile(cfg,"HMT-SLAM"); m_options.defaultMapsInitializers.loadFromConfigFile(cfg,"MetricMaps"); m_options.pf_options.loadFromConfigFile(cfg,"PARTICLE_FILTER"); m_options.KLD_params.loadFromConfigFile(cfg,"KLD"); m_options.AA_options.loadFromConfigFile(cfg,"GRAPH_CUT"); // Topological Loop Closure detector options: m_options.TLC_grid_options.loadFromConfigFile(cfg,"TLC_GRIDMATCHING"); m_options.TLC_fabmap_options.loadFromConfigFile(cfg,"TLC_FABMAP"); m_options.dumpToConsole(); } /*--------------------------------------------------------------- loadOptions ---------------------------------------------------------------*/ void CHMTSLAM::loadOptions( const std::string &configFile ) { ASSERT_( mrpt::system::fileExists(configFile) ); CConfigFile cfg(configFile); loadOptions(cfg); } /*--------------------------------------------------------------- TOptions ---------------------------------------------------------------*/ CHMTSLAM::TOptions::TOptions() { LOG_OUTPUT_DIR = ""; LOG_FREQUENCY = 1; SLAM_METHOD = lsmRBPF_2DLASER; SLAM_MIN_DIST_BETWEEN_OBS = 1.0f; SLAM_MIN_HEADING_BETWEEN_OBS = DEG2RAD(25.0f); MIN_ODOMETRY_STD_XY = 0; MIN_ODOMETRY_STD_PHI = 0; VIEW3D_AREA_SPHERES_HEIGHT = 10.0f; VIEW3D_AREA_SPHERES_RADIUS = 1.0f; random_seed = 1234; TLC_detectors.clear(); stds_Q_no_odo.resize(3); stds_Q_no_odo[0] = stds_Q_no_odo[1] = 0.10f; stds_Q_no_odo[2] = DEG2RAD(4.0f); } /*--------------------------------------------------------------- loadFromConfigFile ---------------------------------------------------------------*/ void CHMTSLAM::TOptions::loadFromConfigFile( const mrpt::utils::CConfigFileBase &source, const std::string &section) { MRPT_LOAD_CONFIG_VAR( LOG_OUTPUT_DIR, string, source, section); MRPT_LOAD_CONFIG_VAR( LOG_FREQUENCY, int, source, section); MRPT_LOAD_CONFIG_VAR_CAST_NO_DEFAULT(SLAM_METHOD, int, TLSlamMethod, source, section); MRPT_LOAD_CONFIG_VAR( SLAM_MIN_DIST_BETWEEN_OBS, float, source, section); MRPT_LOAD_CONFIG_VAR_DEGREES( SLAM_MIN_HEADING_BETWEEN_OBS, source, section); MRPT_LOAD_CONFIG_VAR(MIN_ODOMETRY_STD_XY,float, source,section); MRPT_LOAD_CONFIG_VAR_DEGREES( MIN_ODOMETRY_STD_PHI, source,section); MRPT_LOAD_CONFIG_VAR( VIEW3D_AREA_SPHERES_HEIGHT, float, source, section); MRPT_LOAD_CONFIG_VAR( VIEW3D_AREA_SPHERES_RADIUS, float, source, section); MRPT_LOAD_CONFIG_VAR( random_seed, int, source,section); stds_Q_no_odo[2] = RAD2DEG(stds_Q_no_odo[2]); source.read_vector(section,"stds_Q_no_odo", stds_Q_no_odo, stds_Q_no_odo ); ASSERT_(stds_Q_no_odo.size()==3) stds_Q_no_odo[2] = DEG2RAD(stds_Q_no_odo[2]); std::string sTLC_detectors = source.read_string(section,"TLC_detectors", "", true ); mrpt::system::tokenize(sTLC_detectors,", ",TLC_detectors); std::cout << "TLC_detectors: " << TLC_detectors.size() << std::endl; // load other sub-classes: AA_options.loadFromConfigFile(source,section); } /*--------------------------------------------------------------- dumpToTextStream ---------------------------------------------------------------*/ void CHMTSLAM::TOptions::dumpToTextStream(mrpt::utils::CStream &out) const { out.printf("\n----------- [CHMTSLAM::TOptions] ------------ \n\n"); LOADABLEOPTS_DUMP_VAR( LOG_OUTPUT_DIR, string ); LOADABLEOPTS_DUMP_VAR( LOG_FREQUENCY, int); LOADABLEOPTS_DUMP_VAR( SLAM_METHOD, int); LOADABLEOPTS_DUMP_VAR( SLAM_MIN_DIST_BETWEEN_OBS, float ); LOADABLEOPTS_DUMP_VAR_DEG( SLAM_MIN_HEADING_BETWEEN_OBS ); LOADABLEOPTS_DUMP_VAR( MIN_ODOMETRY_STD_XY, float ); LOADABLEOPTS_DUMP_VAR_DEG( MIN_ODOMETRY_STD_PHI ); LOADABLEOPTS_DUMP_VAR( random_seed, int ); AA_options.dumpToTextStream(out); pf_options.dumpToTextStream(out); KLD_params.dumpToTextStream(out); defaultMapsInitializers.dumpToTextStream(out); TLC_grid_options.dumpToTextStream(out); TLC_fabmap_options.dumpToTextStream(out); } /*--------------------------------------------------------------- isInputQueueEmpty ---------------------------------------------------------------*/ bool CHMTSLAM::isInputQueueEmpty() { bool res; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); res = m_inputQueue.empty(); } return res; } /*--------------------------------------------------------------- inputQueueSize ---------------------------------------------------------------*/ size_t CHMTSLAM::inputQueueSize() { size_t res; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); res = m_inputQueue.size(); } return res; } /*--------------------------------------------------------------- getNextObjectFromInputQueue ---------------------------------------------------------------*/ CSerializablePtr CHMTSLAM::getNextObjectFromInputQueue() { CSerializablePtr obj; { // Wait for critical section CCriticalSectionLocker locker( &m_inputQueue_cs); if (!m_inputQueue.empty()) { obj = m_inputQueue.front(); m_inputQueue.pop(); } } return obj; } /*--------------------------------------------------------------- initializeEmptyMap ---------------------------------------------------------------*/ void CHMTSLAM::initializeEmptyMap() { THypothesisIDSet LMH_hyps; THypothesisID newHypothID = generateHypothesisID(); LMH_hyps.insert( COMMON_TOPOLOG_HYP ); LMH_hyps.insert( newHypothID ); // ------------------------------------ // CLEAR HIERARCHICAL MAP // ------------------------------------ CHMHMapNode::TNodeID firstAreaID; { synch::CCriticalSectionLocker locker( &m_map_cs ); // Initialize hierarchical structures: // ----------------------------------------------------- m_map.clear(); // Create a single node for the starting area: CHMHMapNodePtr firstArea = CHMHMapNode::Create( &m_map ); firstAreaID = firstArea->getID(); firstArea->m_hypotheses = LMH_hyps; CMultiMetricMapPtr emptyMap = CMultiMetricMapPtr(new CMultiMetricMap(&m_options.defaultMapsInitializers) ); firstArea->m_nodeType.setType( "Area" ); firstArea->m_label = generateUniqueAreaLabel(); firstArea->m_annotations.set( NODE_ANNOTATION_METRIC_MAPS, emptyMap, newHypothID ); firstArea->m_annotations.setElemental( NODE_ANNOTATION_REF_POSEID, POSEID_INVALID , newHypothID ); } // end of lock m_map_cs // ------------------------------------ // CLEAR LIST OF HYPOTHESES // ------------------------------------ { synch::CCriticalSectionLocker lock( &m_LMHs_cs ); // Add to the list: m_LMHs.clear(); CLocalMetricHypothesis &newLMH = m_LMHs[newHypothID]; newLMH.m_parent = this; newLMH.m_currentRobotPose = POSEID_INVALID ; // Special case: map is empty newLMH.m_log_w = 0; newLMH.m_ID = newHypothID; newLMH.m_neighbors.clear(); newLMH.m_neighbors.insert( firstAreaID ); newLMH.clearRobotPoses(); } // end of cs // ------------------------------------------ // Create the local SLAM algorithm object // ----------------------------------------- switch( m_options.SLAM_METHOD ) { case lsmRBPF_2DLASER: { if (m_LSLAM_method) delete m_LSLAM_method; m_LSLAM_method = new CLSLAM_RBPF_2DLASER(this); } break; default: THROW_EXCEPTION_FMT("Invalid selection for LSLAM method: %i",(int)m_options.SLAM_METHOD ); }; // ------------------------------------ // Topological LC detectors: // ------------------------------------ { synch::CCriticalSectionLocker lock( &m_topLCdets_cs ); // Clear old list: for (std::deque<CTopLCDetectorBase*>::iterator it=m_topLCdets.begin();it!=m_topLCdets.end();++it) delete *it; m_topLCdets.clear(); // Create new list: // 1: Occupancy Grid matching. // 2: Cummins' image matching. for (vector_string::const_iterator d=m_options.TLC_detectors.begin();d!=m_options.TLC_detectors.end();++d) m_topLCdets.push_back( loopClosureDetector_factory(*d) ); } // ------------------------------------ // Other variables: // ------------------------------------ m_LSLAM_queue.clear(); // ------------------------------------ // Delete log files: // ------------------------------------ if (!m_options.LOG_OUTPUT_DIR.empty()) { mrpt::system::deleteFilesInDirectory( m_options.LOG_OUTPUT_DIR ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMAP_txt" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMAP_3D" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/LSLAM_3D" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/ASSO" ); mrpt::system::createDirectory( m_options.LOG_OUTPUT_DIR + "/HMTSLAM_state" ); } } /*--------------------------------------------------------------- generateUniqueAreaLabel ---------------------------------------------------------------*/ std::string CHMTSLAM::generateUniqueAreaLabel() { return format( "%li", (long int)(m_nextAreaLabel++) ); } /*--------------------------------------------------------------- generatePoseID ---------------------------------------------------------------*/ TPoseID CHMTSLAM::generatePoseID() { return m_nextPoseID++; } /*--------------------------------------------------------------- generateHypothesisID ---------------------------------------------------------------*/ THypothesisID CHMTSLAM::generateHypothesisID() { return m_nextHypID++; } /*--------------------------------------------------------------- getAs3DScene ---------------------------------------------------------------*/ void CHMTSLAM::getAs3DScene( COpenGLScene &scene3D ) { MRPT_UNUSED_PARAM(scene3D); } /*--------------------------------------------------------------- abortedDueToErrors ---------------------------------------------------------------*/ bool CHMTSLAM::abortedDueToErrors() { return m_terminationFlag_LSLAM || m_terminationFlag_TBI || m_terminationFlag_3D_viewer; } /*--------------------------------------------------------------- registerLoopClosureDetector ---------------------------------------------------------------*/ void CHMTSLAM::registerLoopClosureDetector( const std::string &name, CTopLCDetectorBase* (*ptrCreateObject)(CHMTSLAM*) ) { m_registeredLCDetectors[name] = ptrCreateObject; } /*--------------------------------------------------------------- loopClosureDetector_factory ---------------------------------------------------------------*/ CTopLCDetectorBase* CHMTSLAM::loopClosureDetector_factory(const std::string &name) { MRPT_START std::map<std::string,TLopLCDetectorFactory>::const_iterator it=m_registeredLCDetectors.find( name ); if (it==m_registeredLCDetectors.end()) THROW_EXCEPTION_FMT("Invalid value for TLC_detectors: %s", name.c_str() ); return it->second(this); MRPT_END } /*--------------------------------------------------------------- saveState ---------------------------------------------------------------*/ bool CHMTSLAM::saveState( CStream &out ) const { try { out << *this; return true; } catch (...) { return false; } } /*--------------------------------------------------------------- loadState ---------------------------------------------------------------*/ bool CHMTSLAM::loadState( CStream &in ) { try { in >> *this; return true; } catch (...) { return false; } } /*--------------------------------------------------------------- readFromStream ---------------------------------------------------------------*/ void CHMTSLAM::readFromStream(mrpt::utils::CStream &in,int version) { switch(version) { case 0: { // Acquire all critical sections before! // ------------------------------------------- //std::map< THypothesisID, CLocalMetricHypothesis >::const_iterator it; //CCriticalSectionLocker LMHs( & m_LMHs_cs ); //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); CCriticalSectionLocker lock_map( &m_map_cs ); // Data: in >> m_nextAreaLabel >> m_nextPoseID >> m_nextHypID; // The HMT-MAP: in >> m_map; // The LMHs: in >> m_LMHs; // Save options??? Better allow changing them... // Release all critical sections: //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; } /*--------------------------------------------------------------- writeToStream Implements the writing to a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CHMTSLAM::writeToStream(mrpt::utils::CStream &out, int *version) const { if (version) *version = 0; else { // Acquire all critical sections before! // ------------------------------------------- //std::map< THypothesisID, CLocalMetricHypothesis >::const_iterator it; //CCriticalSectionLocker LMHs( & m_LMHs_cs ); //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); CCriticalSectionLocker lock_map( &m_map_cs ); // Data: out << m_nextAreaLabel << m_nextPoseID << m_nextHypID; // The HMT-MAP: out << m_map; // The LMHs: out << m_LMHs; // Save options??? Better allow changing them... // Release all critical sections: //for (it=m_LMHs.begin();it!=m_LMHs.end();it++) it->second.m_lock.enter(); } }
29.088193
113
0.554942
yhexie
225116285d24ca6e60ba3efca6ba3cd68e515985
6,441
cpp
C++
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
4
2021-08-02T22:57:17.000Z
2021-12-26T16:45:17.000Z
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
null
null
null
cppillr/parser.cpp
dacap/cppillr
4b67403aab09c24d70c417e85567b48478f5aab0
[ "MIT" ]
null
null
null
// Copyright (C) 2019-2021 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #include "cppillr/parser.h" #include <memory> void Parser::parse(const LexData& lex) { data.fn = lex.fn; lex_data = &lex; goto_token(-1); dcl_seq(); } // Converts a function body that was "fast parsed" (only tokens) into // AST nodes. void Parser::parse_function_body(const LexData& lex, FunctionNode* f) { data.fn = lex.fn; lex_data = &lex; goto_token(f->body->beg_tok); f->body->block = compound_statement(); } bool Parser::dcl_seq() { while (next_token().kind != TokenKind::Eof) { if (!dcl()) return false; } return true; } bool Parser::dcl() { if (is_builtin_type()) { FunctionNode* f = function_definition(); if (f) { data.functions.push_back(f); return true; } } return false; } FunctionNode* Parser::function_definition() { if (is_builtin_type()) { auto f = std::make_unique<FunctionNode>(); f->builtin_type = (Keyword)tok->i; expect(TokenKind::Identifier, "expecting identifier for function"); f->name = lex_data->id_text(*tok); f->params = function_params(); if (!f->params) return nullptr; f->body = function_body_fast(); if (!f->body) return nullptr; return f.release(); } return nullptr; } ParamsNode* Parser::function_params() { auto ps = std::make_unique<ParamsNode>(); expect('('); while (next_token().kind != TokenKind::Eof) { if (is_punctuator(')')) { return ps.release(); } else if (is_builtin_type()) { auto p = std::make_unique<ParamNode>(); p->builtin_type = (Keyword)tok->i; next_token(); // Pointers while (is_punctuator('*')) // TODO add this info to param type next_token(); if (is(TokenKind::Identifier)) { // Param with name p->name = lex_data->id_text(*tok); next_token(); if (is_punctuator(')')) { ps->params.push_back(p.get()); p.release(); return ps.release(); } else if (!is_punctuator(',')) error("expecting ',' or ')' after param name"); } // Param without name else if (is_punctuator(')')) { ps->params.push_back(p.get()); p.release(); return ps.release(); } else if (!is_punctuator(',')) error("expecting ',', ')', or param name after param type"); ps->params.push_back(p.get()); p.release(); } else { error("expecting ')' or type"); } } return nullptr; } BodyNode* Parser::function_body_fast() { auto b = std::make_unique<BodyNode>(); int scope = 0; expect('{'); b->lex_i = lex_i; b->beg_tok = tok_i; while (next_token().kind != TokenKind::Eof) { if (is_punctuator('}')) { if (scope == 0) { b->end_tok = tok_i; return b.release(); } else --scope; } else if (is_punctuator('{')) { ++scope; } } error("expecting '}' before EOF"); return nullptr; } CompoundStmt* Parser::compound_statement() { auto b = std::make_unique<CompoundStmt>(); if (!is_punctuator('{')) error("expecting '{' to start a block"); next_token(); // Skip '{' while (tok->kind != TokenKind::Eof) { if (is_punctuator('}')) { return b.release(); } else { auto s = statement(); if (s) b->stmts.push_back(s); else return nullptr; } } error("expecting '}' before EOF"); return nullptr; } Stmt* Parser::statement() { if (is_punctuator(';')) { next_token(); // Skip ';', empty expression return nullptr; } else if (tok->kind == TokenKind::Keyword) { // Return statement switch (tok->i) { case key_return: return return_stmt(); default: error("not supported keyword %s", keywords_id[tok->i].c_str()); break; } } error("expecting '}' or statement"); return nullptr; } Return* Parser::return_stmt() { auto r = std::make_unique<Return>(); bool err = false; if (next_token().kind != TokenKind::Eof) { if (!is_punctuator(';')) { r->expr = expression(); if (!r->expr) err = true; } if (is_punctuator(';')) { next_token(); // Skip ';', return with expression } } else err = true; if (err) error("expecting ';' or expression for return statement"); return r.release(); } Expr* Parser::expression() { return additive_expression(); } // [expr.add] Expr* Parser::additive_expression() { std::unique_ptr<Expr> e(multiplicative_expression()); if (!e) return nullptr; while (is_punctuator('+') || is_punctuator('-')) { auto be = std::make_unique<BinExpr>(); be->op = tok->i; be->lhs = e.release(); next_token(); be->rhs = multiplicative_expression(); e = std::move(be); } return e.release(); } // [expr.mul] Expr* Parser::multiplicative_expression() { std::unique_ptr<Expr> e(primary_expression()); if (!e) return nullptr; while (is_punctuator('*') || is_punctuator('/') || is_punctuator('%')) { auto be = std::make_unique<BinExpr>(); be->op = tok->i; be->lhs = e.release(); next_token(); be->rhs = primary_expression(); if (!be->rhs) error("expecting expression after %c", be->op); e = std::move(be); } return e.release(); } // [expr.prim] Expr* Parser::primary_expression() { if (is_punctuator('(')) { next_token(); // Skip '(' std::unique_ptr<Expr> e(expression()); if (!is_punctuator(')')) error("expected ')' to finish expression"); next_token(); return e.release(); } else if (is_punctuator('*') || is_punctuator('&') || is_punctuator('+') || is_punctuator('-') || is_punctuator('!') || is_punctuator('~')) { auto be = std::make_unique<UnaryExpr>(); be->op = tok->i; next_token(); be->operand = primary_expression(); if (!be->operand) error("expected primary expression after '-'"); return be.release(); } else if (is(TokenKind::NumericConstant)) { auto l = std::make_unique<Literal>(); l->value = std::strtol(lex_data->id_text(*tok).c_str(), nullptr, 0); next_token(); return l.release(); } return nullptr; }
20.912338
72
0.567148
dacap
2252afa57cc8ec9b2d19325148cd3720d7dd5c34
7,530
cc
C++
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
null
null
null
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
2
2018-05-04T13:43:45.000Z
2018-08-27T13:53:45.000Z
cvmfs/receiver/payload_processor.cc
amadio/cvmfs
2cc5dc22c6c163e8515229006a0c6f8fbad9c23d
[ "BSD-3-Clause" ]
null
null
null
/** * This file is part of the CernVM File System. */ #include "payload_processor.h" #include <fcntl.h> #include <unistd.h> #include <vector> #include "logging.h" #include "params.h" #include "util/posix.h" #include "util/string.h" namespace { const size_t kConsumerBuffer = 10 * 1024 * 1024; // 10 MB } namespace receiver { FileInfo::FileInfo() : handle(NULL), total_size(0), current_size(0), hash_context(), hash_buffer() {} FileInfo::FileInfo(const ObjectPackBuild::Event& event) : handle(NULL), total_size(event.size), current_size(0), hash_context(shash::ContextPtr(event.id.algorithm)), hash_buffer(hash_context.size, 0) { hash_context.buffer = &hash_buffer[0]; shash::Init(hash_context); } FileInfo::FileInfo(const FileInfo& other) : handle(other.handle), total_size(other.total_size), current_size(other.current_size), hash_context(other.hash_context), hash_buffer(other.hash_buffer) { hash_context.buffer = &hash_buffer[0]; } FileInfo& FileInfo::operator=(const FileInfo& other) { handle = other.handle; total_size = other.total_size; current_size = other.current_size; hash_context = other.hash_context; hash_buffer = other.hash_buffer; hash_context.buffer = &hash_buffer[0]; return *this; } PayloadProcessor::PayloadProcessor() : pending_files_(), current_repo_(), uploader_(), temp_dir_(), num_errors_(0), statistics_(NULL) {} PayloadProcessor::~PayloadProcessor() {} PayloadProcessor::Result PayloadProcessor::Process( int fdin, const std::string& header_digest, const std::string& path, uint64_t header_size) { LogCvmfs(kLogReceiver, kLogSyslog, "PayloadProcessor - lease_path: %s, header digest: %s, header " "size: %ld", path.c_str(), header_digest.c_str(), header_size); const size_t first_slash_idx = path.find('/', 0); current_repo_ = path.substr(0, first_slash_idx); Result init_result = Initialize(); if (init_result != kSuccess) { return init_result; } // Set up object pack deserialization shash::Any digest = shash::MkFromHexPtr(shash::HexPtr(header_digest)); ObjectPackConsumer deserializer(digest, header_size); deserializer.RegisterListener(&PayloadProcessor::ConsumerEventCallback, this); int nb = 0; ObjectPackBuild::State consumer_state = ObjectPackBuild::kStateContinue; std::vector<unsigned char> buffer(kConsumerBuffer, 0); do { nb = read(fdin, &buffer[0], buffer.size()); consumer_state = deserializer.ConsumeNext(nb, &buffer[0]); if (consumer_state != ObjectPackBuild::kStateContinue && consumer_state != ObjectPackBuild::kStateDone) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: %d encountered when consuming object " "pack.", consumer_state); break; } } while (nb > 0 && consumer_state != ObjectPackBuild::kStateDone); assert(pending_files_.empty()); Result res = Finalize(); deserializer.UnregisterListeners(); return res; } void PayloadProcessor::ConsumerEventCallback( const ObjectPackBuild::Event& event) { std::string path(""); if (event.object_type == ObjectPack::kCas) { path = event.id.MakePath(); } else if (event.object_type == ObjectPack::kNamed) { path = event.object_name; } else { // kEmpty - this is an error. LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Event received with unknown object."); num_errors_++; return; } FileIterator it = pending_files_.find(event.id); if (it == pending_files_.end()) { // Schedule file upload if it's not being uploaded yet. // Uploaders later check if the file is already present // in the upstream storage and will not upload it twice. FileInfo info(event); // info.handle is later deleted by FinalizeStreamedUpload info.handle = uploader_->InitStreamedUpload(NULL); pending_files_[event.id] = info; } FileInfo& info = pending_files_[event.id]; void *buf_copied = smalloc(event.buf_size); memcpy(buf_copied, event.buf, event.buf_size); upload::AbstractUploader::UploadBuffer buf(event.buf_size, buf_copied); uploader_->ScheduleUpload(info.handle, buf, upload::AbstractUploader::MakeClosure( &PayloadProcessor::OnUploadJobComplete, this, buf_copied)); shash::Update(static_cast<const unsigned char*>(event.buf), event.buf_size, info.hash_context); info.current_size += event.buf_size; if (info.current_size == info.total_size) { shash::Any file_hash(event.id.algorithm); shash::Final(info.hash_context, &file_hash); if (file_hash != event.id) { LogCvmfs( kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Hash mismatch for unpacked file: event " "size: %ld, file size: %ld, event hash: %s, file hash: %s", event.size, info.current_size, event.id.ToString(true).c_str(), file_hash.ToString(true).c_str()); num_errors_++; return; } // override final remote path if not CAS object if (event.object_type == ObjectPack::kNamed) { info.handle->remote_path = path; } uploader_->ScheduleCommit(info.handle, event.id); pending_files_.erase(event.id); } } void PayloadProcessor::OnUploadJobComplete( const upload::UploaderResults &results, void *buffer) { free(buffer); } void PayloadProcessor::SetStatistics(perf::Statistics *st) { statistics_ = new perf::StatisticsTemplate("Publish", st); } PayloadProcessor::Result PayloadProcessor::Initialize() { Params params; if (!GetParamsFromFile(current_repo_, &params)) { LogCvmfs( kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Could not get configuration parameters."); return kOtherError; } const std::string spooler_temp_dir = GetSpoolerTempDir(params.spooler_configuration); assert(!spooler_temp_dir.empty()); assert(MkdirDeep(spooler_temp_dir + "/receiver", 0770, true)); temp_dir_ = RaiiTempDir::Create(spooler_temp_dir + "/receiver/payload_processor"); upload::SpoolerDefinition definition( params.spooler_configuration, params.hash_alg, params.compression_alg, params.generate_legacy_bulk_chunks, params.use_file_chunking, params.min_chunk_size, params.avg_chunk_size, params.max_chunk_size, "dummy_token", "dummy_key"); uploader_.Destroy(); // configure the uploader environment uploader_ = upload::AbstractUploader::Construct(definition); if (!uploader_) { LogCvmfs(kLogSpooler, kLogWarning, "Failed to initialize backend upload " "facility in PayloadProcessor."); return kUploaderError; } if (statistics_.IsValid()) { uploader_->InitCounters(statistics_); } return kSuccess; } PayloadProcessor::Result PayloadProcessor::Finalize() { uploader_->WaitForUpload(); temp_dir_.Destroy(); const unsigned num_uploader_errors = uploader_->GetNumberOfErrors(); uploader_->TearDown(); if (num_uploader_errors > 0) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: Uploader - %d upload(s) failed.", num_uploader_errors); return kUploaderError; } if (GetNumErrors() > 0) { LogCvmfs(kLogReceiver, kLogSyslogErr, "PayloadProcessor - error: % unpacking error(s).", GetNumErrors()); return kOtherError; } return kSuccess; } } // namespace receiver
28.740458
80
0.691368
amadio
2255c2bc0f12bbaf4f04a3925c00b7c81bee2a5c
557
cpp
C++
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
source/dataset/CameraMgr.cpp
xzrunner/easyeditor3
61c89c8534d1342fb2890d7e6218fd7614410861
[ "MIT" ]
null
null
null
#include "ee3/CameraMgr.h" #include <painting3/OrthoCam.h> namespace ee3 { CameraMgr::CameraMgr(bool only3d) : m_curr(CAM_3D) { assert(m_cams[CAM_3D] == nullptr); if (!only3d) { m_cams[CAM_XZ] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_XZ); m_cams[CAM_XY] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_XY); m_cams[CAM_ZY] = std::make_shared<pt3::OrthoCam>(pt3::OrthoCam::VP_ZY); } } const pt0::CameraPtr& CameraMgr::SwitchToNext() { m_curr = static_cast<CameraType>((m_curr + 1) % CAM_MAX_COUNT); return m_cams[m_curr]; } }
20.62963
73
0.70377
xzrunner
225cbc1165f4d8ebe4aad018a0bded7ee16a7ee4
8,733
cpp
C++
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
iotcloud/src/v20210408/model/CertInfo.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iotcloud/v20210408/model/CertInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iotcloud::V20210408::Model; using namespace std; CertInfo::CertInfo() : m_certNameHasBeenSet(false), m_certSNHasBeenSet(false), m_issuerNameHasBeenSet(false), m_subjectHasBeenSet(false), m_createTimeHasBeenSet(false), m_effectiveTimeHasBeenSet(false), m_expireTimeHasBeenSet(false), m_certTextHasBeenSet(false) { } CoreInternalOutcome CertInfo::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("CertName") && !value["CertName"].IsNull()) { if (!value["CertName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertName` IsString=false incorrectly").SetRequestId(requestId)); } m_certName = string(value["CertName"].GetString()); m_certNameHasBeenSet = true; } if (value.HasMember("CertSN") && !value["CertSN"].IsNull()) { if (!value["CertSN"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertSN` IsString=false incorrectly").SetRequestId(requestId)); } m_certSN = string(value["CertSN"].GetString()); m_certSNHasBeenSet = true; } if (value.HasMember("IssuerName") && !value["IssuerName"].IsNull()) { if (!value["IssuerName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.IssuerName` IsString=false incorrectly").SetRequestId(requestId)); } m_issuerName = string(value["IssuerName"].GetString()); m_issuerNameHasBeenSet = true; } if (value.HasMember("Subject") && !value["Subject"].IsNull()) { if (!value["Subject"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.Subject` IsString=false incorrectly").SetRequestId(requestId)); } m_subject = string(value["Subject"].GetString()); m_subjectHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_createTime = value["CreateTime"].GetUint64(); m_createTimeHasBeenSet = true; } if (value.HasMember("EffectiveTime") && !value["EffectiveTime"].IsNull()) { if (!value["EffectiveTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.EffectiveTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_effectiveTime = value["EffectiveTime"].GetUint64(); m_effectiveTimeHasBeenSet = true; } if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull()) { if (!value["ExpireTime"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `CertInfo.ExpireTime` IsUint64=false incorrectly").SetRequestId(requestId)); } m_expireTime = value["ExpireTime"].GetUint64(); m_expireTimeHasBeenSet = true; } if (value.HasMember("CertText") && !value["CertText"].IsNull()) { if (!value["CertText"].IsString()) { return CoreInternalOutcome(Core::Error("response `CertInfo.CertText` IsString=false incorrectly").SetRequestId(requestId)); } m_certText = string(value["CertText"].GetString()); m_certTextHasBeenSet = true; } return CoreInternalOutcome(true); } void CertInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_certNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certName.c_str(), allocator).Move(), allocator); } if (m_certSNHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertSN"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certSN.c_str(), allocator).Move(), allocator); } if (m_issuerNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "IssuerName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_issuerName.c_str(), allocator).Move(), allocator); } if (m_subjectHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Subject"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_subject.c_str(), allocator).Move(), allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_createTime, allocator); } if (m_effectiveTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EffectiveTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_effectiveTime, allocator); } if (m_expireTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpireTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_expireTime, allocator); } if (m_certTextHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CertText"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_certText.c_str(), allocator).Move(), allocator); } } string CertInfo::GetCertName() const { return m_certName; } void CertInfo::SetCertName(const string& _certName) { m_certName = _certName; m_certNameHasBeenSet = true; } bool CertInfo::CertNameHasBeenSet() const { return m_certNameHasBeenSet; } string CertInfo::GetCertSN() const { return m_certSN; } void CertInfo::SetCertSN(const string& _certSN) { m_certSN = _certSN; m_certSNHasBeenSet = true; } bool CertInfo::CertSNHasBeenSet() const { return m_certSNHasBeenSet; } string CertInfo::GetIssuerName() const { return m_issuerName; } void CertInfo::SetIssuerName(const string& _issuerName) { m_issuerName = _issuerName; m_issuerNameHasBeenSet = true; } bool CertInfo::IssuerNameHasBeenSet() const { return m_issuerNameHasBeenSet; } string CertInfo::GetSubject() const { return m_subject; } void CertInfo::SetSubject(const string& _subject) { m_subject = _subject; m_subjectHasBeenSet = true; } bool CertInfo::SubjectHasBeenSet() const { return m_subjectHasBeenSet; } uint64_t CertInfo::GetCreateTime() const { return m_createTime; } void CertInfo::SetCreateTime(const uint64_t& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool CertInfo::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } uint64_t CertInfo::GetEffectiveTime() const { return m_effectiveTime; } void CertInfo::SetEffectiveTime(const uint64_t& _effectiveTime) { m_effectiveTime = _effectiveTime; m_effectiveTimeHasBeenSet = true; } bool CertInfo::EffectiveTimeHasBeenSet() const { return m_effectiveTimeHasBeenSet; } uint64_t CertInfo::GetExpireTime() const { return m_expireTime; } void CertInfo::SetExpireTime(const uint64_t& _expireTime) { m_expireTime = _expireTime; m_expireTimeHasBeenSet = true; } bool CertInfo::ExpireTimeHasBeenSet() const { return m_expireTimeHasBeenSet; } string CertInfo::GetCertText() const { return m_certText; } void CertInfo::SetCertText(const string& _certText) { m_certText = _certText; m_certTextHasBeenSet = true; } bool CertInfo::CertTextHasBeenSet() const { return m_certTextHasBeenSet; }
27.121118
140
0.675255
suluner
225d27d248e883e0c054df3a946207a9526d4dc9
4,619
cpp
C++
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
8
2022-02-03T18:09:23.000Z
2022-02-09T16:05:28.000Z
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
null
null
null
Source/CheatSheetUI/Private/UI/UI_CheatView.cpp
tomshinton/CheatSheetPlugin
2d2f8d7b7b6370a2815315c0bb21c613a915ee39
[ "MIT" ]
null
null
null
// CheatSheet Plugin - Tom Shinton 2019 #include "CheatSheetUI/Public/UI/UI_CheatView.h" #include "CheatSheetUI/Public/UI/Entries/UI_CategoryEntry.h" #include "CheatSheetUI/Public/UI/Entries/UI_CheatEntry.h" #include <Runtime/UMG/Public/Components/ScrollBox.h> #include <Runtime/UMG/Public/Components/VerticalBox.h> DEFINE_LOG_CATEGORY_STATIC(CheatViewLog, Log, Log); UUI_CheatView::UUI_CheatView(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , CategoryBox(nullptr) , CheatBox(nullptr) , CheatScrollBox(nullptr) , CheatCategoryClass(nullptr) , CheatEntryClass(nullptr) , Categories() , OnNewCategoryRequested() , OnNewSelection() , RequestCallback(nullptr) , Entries() , CurrentSelection() , CurrentSelectionIndex(0) , TotalEntries(0) {} void UUI_CheatView::NativeConstruct() { Super::NativeConstruct(); RequestCallback = [WeakThis = TWeakObjectPtr<UUI_CheatView>(this), this](const FCheatCategory& InRequestingCategory) { if (WeakThis.IsValid()) { RequestViewForCategory(InRequestingCategory); } }; } void UUI_CheatView::RequestViewForCategory(const FCheatCategory& InCheatCategory) { TotalEntries = 0; CurrentSelectionIndex = 0; if (CategoryBox != nullptr && CheatBox != nullptr) { if (CheatCategoryClass != nullptr && CheatEntryClass != nullptr) { CategoryBox->ClearChildren(); CheatBox->ClearChildren(); const TArray<FCheatCategory> CachedCategories = InCheatCategory.GetSubCategories(); for (const FCheatCategory& Category : CachedCategories) { UUI_CategoryEntry* NewCategory = CreateWidget<UUI_CategoryEntry>(this, CheatCategoryClass); NewCategory->SetCategory(Category); NewCategory->SetRequestCallback(RequestCallback); CategoryBox->AddChild(NewCategory); } const TArray<FCachedCheat> CachedCheats = InCheatCategory.GetCheats(); for (const FCachedCheat& Cheat : CachedCheats) { UUI_CheatEntry* NewCheat = CreateWidget<UUI_CheatEntry>(this, CheatEntryClass); NewCheat->SetCheat(Cheat); CheatBox->AddChild(NewCheat); } } } OnNewCategoryRequested.Broadcast(InCheatCategory); ApplyEntryNumbers(); ApplyNewSelectionIndex(); } void UUI_CheatView::RequestHomeView(const TArray<FCheatCategory>& InCheatCategories) { TotalEntries = 0; CurrentSelectionIndex = 0; if (CheatCategoryClass != nullptr) { if (CheatCategoryClass != nullptr && CheatEntryClass != nullptr) { CategoryBox->ClearChildren(); CheatBox->ClearChildren(); for (const FCheatCategory& Category : InCheatCategories) { UUI_CategoryEntry* NewCategory = CreateWidget<UUI_CategoryEntry>(this, CheatCategoryClass); NewCategory->SetCategory(Category); NewCategory->SetRequestCallback(RequestCallback); CategoryBox->AddChild(NewCategory); } } } ApplyEntryNumbers(); ApplyNewSelectionIndex(); } void UUI_CheatView::SynchronizeProperties() { Super::SynchronizeProperties(); RequestHomeView(Categories); } void UUI_CheatView::ConfirmSelection() { if (CurrentSelection.IsValid()) { CurrentSelection->ExecuteEntry(); } } void UUI_CheatView::UpSelection() { CurrentSelectionIndex == 0 ? CurrentSelectionIndex = TotalEntries - 1 : CurrentSelectionIndex--; ApplyNewSelectionIndex(); } void UUI_CheatView::DownSelection() { CurrentSelectionIndex == TotalEntries - 1 ? CurrentSelectionIndex = 0 : CurrentSelectionIndex++; ApplyNewSelectionIndex(); } void UUI_CheatView::ApplyEntryNumbers() { if (CheatBox != nullptr && CategoryBox != nullptr) { for (int32 i = 0; i < CategoryBox->GetChildrenCount(); ++i) { UWidget* Child = CategoryBox->GetChildAt(i); if (ICheatEntryInterface* Entry = Cast<ICheatEntryInterface>(Child)) { Entry->SetEntryNumber(TotalEntries); Entries.Add(TotalEntries, Entry); TotalEntries++; } } for (int32 i = 0; i < CheatBox->GetChildrenCount(); ++i) { UWidget* Child = CheatBox->GetChildAt(i); if (ICheatEntryInterface* Entry = Cast<ICheatEntryInterface>(Child)) { Entry->SetEntryNumber(TotalEntries); Entries.Add(TotalEntries, Entry); TotalEntries++; } } } } void UUI_CheatView::ApplyNewSelectionIndex() { const TWeakInterfacePtr<ICheatEntryInterface> OldSelection = CurrentSelection; if (CurrentSelection.IsValid()) { CurrentSelection->SetIsSelected(false); } CurrentSelection = Entries[CurrentSelectionIndex]; if (CurrentSelection.IsValid()) { CurrentSelection->SetIsSelected(true); OnNewSelection.Broadcast(OldSelection, CurrentSelection); if(CheatScrollBox != nullptr) { CheatScrollBox->ScrollWidgetIntoView(&CurrentSelection->GetWidget()); } } }
24.833333
117
0.746698
tomshinton
2262f39071bd2012923504ddb5dbbab5aed024f3
2,102
cpp
C++
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
0rgb/example_2/src/inversecolorpsaceadjustement.cpp
Enkelena/oRGB
c7e250f0a28b8db073d60c05f693ad15489e271e
[ "MIT" ]
null
null
null
#include "inversecolorpsaceadjustement.hpp" Eigen::Matrix3d Inverse::rotatePoint(double angle) { Eigen::Matrix3d _matrix; _matrix << 1, 0, 0, 0, 1, 0, 0, 0, 1; _matrix(1,1) = cos(angle * M_PI / 180); _matrix(1,2) = -sin(angle * M_PI / 180); _matrix(2,1) = sin(angle * M_PI / 180); _matrix(2,2) = cos(angle * M_PI / 180); return _matrix; } cv::Mat Inverse::fullRotation(cv::Mat img1) { double thetaAngle=0; double r{0},b{0},g{0}; cv::MatIterator_<cv::Vec3d> itd, end; for( itd=img1.begin<cv::Vec3d>(); itd!= img1.end<cv::Vec3d>();++itd) { r = (*itd)[0]; g = (*itd)[1]; b = (*itd)[2]; double theta = atan2(b, g); double newTheta=0; if (theta< M_PI / 2) { newTheta = (2/3)*theta; } if((theta>= (M_PI /3)) && (theta <=(5*M_PI/3))) { newTheta = M_PI/3 + 4/3*(theta-M_PI/2); } if((theta> 5*M_PI / 3) && (theta <(2*M_PI)) ) { newTheta = (2/3)*theta; } thetaAngle=(newTheta-theta); Eigen::Vector3d _local {r,g,b}; _local = rotatePoint(thetaAngle) * _local; (*itd)[0]=(_local[0]); (*itd)[1]=(_local[1]); (*itd)[2]=(_local[2]); } return img1; } cv::Mat Inverse::setlinearImage(cv::Mat img1) { Eigen::Matrix3d linear_matrix; linear_matrix << 1.0000, 0.1140, 0.7436, 1.0000, 0.1140, -0.4111, 1.0000, -0.8860,0.1663; double gamma = 2.2f; cv::MatIterator_<cv::Vec3d> itd, end; for( itd=img1.begin<cv::Vec3d>(); itd!= img1.end<cv::Vec3d>();++itd) { Eigen::Vector3d _local {(*itd)[0], (*itd)[1], (*itd)[2]}; _local = linear_matrix * _local; (*itd)[0]=(_local(0))*255; (*itd)[1]=(_local(1))*255; (*itd)[2]=(_local(2))*255; (*itd)[0] = pow((static_cast <double>((*itd)[0]) / 255.0 ),gamma)*255; (*itd)[1] = pow((static_cast <double>((*itd)[1]) / 255.0 ),gamma)*255; (*itd)[2] = pow((static_cast <double>((*itd)[2]) / 255.0 ),gamma)*255; } return img1; }
25.02381
77
0.508088
Enkelena
226c7b014b66da63b49119fed307734bbcca44b8
5,462
cpp
C++
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
2
2021-04-28T20:51:25.000Z
2021-04-28T20:51:38.000Z
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
src/component/renderer.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
#include "renderer.hpp" #include "../io/io.hpp" #include "transform.hpp" #include "../object/camera.hpp" Renderer::Renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) : Component("Renderer"), model(model), material(material), render_mode(render_mode), receive_shadow(true), display_texture(true) {} Renderer::Renderer(const Renderer& renderer) : Component(renderer), model(renderer.model->clone2()), material(renderer.material->clone()), render_mode(renderer.render_mode), receive_shadow(renderer.receive_shadow), display_texture(renderer.display_texture) {} std::shared_ptr<Renderer> Renderer::make_renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) { std::shared_ptr<Renderer> renderer(new Renderer(model, material, render_mode)); return renderer; } std::shared_ptr<Renderer> pepng::make_renderer(std::shared_ptr<Model> model, std::shared_ptr<Material> material, GLenum render_mode) { return Renderer::make_renderer(model, material, render_mode); } Renderer* Renderer::clone_implementation() { return new Renderer(*this); } void Renderer::init(std::shared_ptr<WithComponents> parent) { this->__transform = parent->get_component<Transform>(); if (this->__transform == nullptr) { std::stringstream ss; ss << *parent << " has no transform." << std::endl; std::cout << ss.str() << std::endl; throw std::runtime_error(ss.str()); } } void Renderer::render(std::shared_ptr<WithComponents> parent, GLuint shaderProgram) { if(!this->model->is_init()) this->model->delayed_init(); if(this->model->vao() == -1 || !this->active()) return; glUseProgram(shaderProgram); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, this->material->texture->gl_index()); glUniform1i( glGetUniformLocation(shaderProgram, "u_texture"), 1 ); GLuint uWorld = glGetUniformLocation(shaderProgram, "u_world"); if (uWorld >= 0) { auto worldMatrix = this->__transform->parent_matrix * glm::translate(glm::mat4(1.0f), this->model->offset()) * this->__transform->world_matrix() * glm::translate(glm::mat4(1.0f), -this->model->offset()); glUniformMatrix4fv( uWorld, 1, GL_FALSE, glm::value_ptr(worldMatrix) ); } GLuint uReceiveShadow = glGetUniformLocation(shaderProgram, "u_receive_shadow"); if(uReceiveShadow >= 0) { glUniform1f( uReceiveShadow, this->receive_shadow ); } GLuint uDisplayTexture = glGetUniformLocation(shaderProgram, "u_display_texture"); if(uDisplayTexture >= 0) { glUniform1f( uDisplayTexture, this->display_texture ); } glBindVertexArray(this->model->vao()); if(this->model->has_element_array()) { glDrawElements( this->render_mode, this->model->count(), GL_UNSIGNED_INT, 0 ); } else { glDrawArrays( this->render_mode, 0, this->model->count() ); } } void Renderer::render(std::shared_ptr<WithComponents> parent) { auto shaderProgram = this->material->shader_program(); glUseProgram(shaderProgram); if(Camera::current_camera == nullptr) { std::cout << "No current camera set." << std::endl; throw std::runtime_error("No current camera set."); } Camera::current_camera->render(shaderProgram); for(auto light : Light::lights) { light->render(shaderProgram); } this->render(parent, shaderProgram); } #ifdef IMGUI void Renderer::imgui() { Component::imgui(); ImGui::LabelText("Name", this->model->name().c_str()); std::stringstream ss; ss << this->model->count(); ImGui::LabelText("Index Count", ss.str().c_str()); const char* items[] = { "Lines", "Points", "Triangles" }; static int item_current_idx = -1; if (item_current_idx == -1) { switch(this->render_mode) { case GL_TRIANGLES: item_current_idx = 2; break; case GL_POINTS: item_current_idx = 1; break; case GL_LINES: item_current_idx = 0; } } const char* combo_label = items[item_current_idx]; if (ImGui::BeginCombo("Mode", combo_label)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { const bool is_selected = (item_current_idx == n); if (ImGui::Selectable(items[n], is_selected)) { item_current_idx = n; switch(item_current_idx) { case 2: this->render_mode = GL_TRIANGLES; break; case 1: this->render_mode = GL_POINTS; break; case 0: this->render_mode = GL_LINES; break; } } if (is_selected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } ImGui::Checkbox("Texture", &this->display_texture); ImGui::Checkbox("Shadow", &this->receive_shadow); } #endif
27.174129
137
0.584401
pepng-CU
226e61ddb34305690040a52e48dc35f82d3e7422
42
cpp
C++
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
lab3/smarttree/main.cpp
Adrjanjan/JiMP-Exercises
0c5de5878bcf0ede27fedcdf3cebbe081679e180
[ "MIT" ]
null
null
null
// // Created by adrja on 22.03.2018. //
8.4
34
0.571429
Adrjanjan
227142a71df76ed4b47ffc680d9db3ce94ea0582
3,803
cpp
C++
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
1
2021-07-21T05:34:18.000Z
2021-07-21T05:34:18.000Z
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
null
null
null
src/serac/physics/utilities/state_manager.cpp
jamiebramwell/serac
a839f8dc1560b1ec2b3d542f23a5f2ac71f2a962
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019-2021, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "serac/physics/utilities/state_manager.hpp" namespace serac { // Definition of extern variable QuadratureData<void> dummy_qdata; // Initialize StateManager's static members - both of these will be fully initialized in StateManager::initialize std::optional<axom::sidre::MFEMSidreDataCollection> StateManager::datacoll_; bool StateManager::is_restart_ = false; std::string StateManager::collection_name_ = ""; std::vector<std::unique_ptr<SyncableData>> StateManager::syncable_data_; void StateManager::initialize(axom::sidre::DataStore& ds, const std::string& collection_name_prefix, const std::optional<int> cycle_to_load) { // If the global object has already been initialized, clear it out if (datacoll_) { reset(); } collection_name_ = collection_name_prefix + "_datacoll"; auto global_grp = ds.getRoot()->createGroup(collection_name_ + "_global"); auto bp_index_grp = global_grp->createGroup("blueprint_index/" + collection_name_); auto domain_grp = ds.getRoot()->createGroup(collection_name_); // Needs to be configured to own the mesh data so all mesh data is saved to datastore/output file const bool owns_mesh_data = true; datacoll_.emplace(collection_name_, bp_index_grp, domain_grp, owns_mesh_data); datacoll_->SetComm(MPI_COMM_WORLD); if (cycle_to_load) { is_restart_ = true; // NOTE: Load invalidates previous Sidre pointers datacoll_->Load(*cycle_to_load); datacoll_->SetGroupPointers( ds.getRoot()->getGroup(collection_name_ + "_global/blueprint_index/" + collection_name_), ds.getRoot()->getGroup(collection_name_)); SLIC_ERROR_ROOT_IF(datacoll_->GetBPGroup()->getNumGroups() == 0, "Loaded datastore is empty, was the datastore created on a " "different number of nodes?"); datacoll_->UpdateStateFromDS(); datacoll_->UpdateMeshAndFieldsFromDS(); } else { datacoll_->SetCycle(0); // Iteration counter datacoll_->SetTime(0.0); // Simulation time } } FiniteElementState StateManager::newState(FiniteElementState::Options&& options) { SLIC_ERROR_ROOT_IF(!datacoll_, "Serac's datacollection was not initialized - call StateManager::initialize first"); const std::string name = options.name; if (is_restart_) { auto field = datacoll_->GetParField(name); return {mesh(), *field, name}; } else { SLIC_ERROR_ROOT_IF(datacoll_->HasField(name), fmt::format("Serac's datacollection was already given a field named '{0}'", name)); options.alloc_gf = false; FiniteElementState state(mesh(), std::move(options)); datacoll_->RegisterField(name, &(state.gridFunc())); // Now that it's been allocated, we can set it to zero state.gridFunc() = 0.0; return state; } } void StateManager::save(const double t, const int cycle) { SLIC_ERROR_ROOT_IF(!datacoll_, "Serac's datacollection was not initialized - call StateManager::initialize first"); for (const auto& data : syncable_data_) { data->sync(); } datacoll_->SetTime(t); datacoll_->SetCycle(cycle); datacoll_->Save(); } void StateManager::setMesh(std::unique_ptr<mfem::ParMesh> mesh) { datacoll_->SetMesh(mesh.release()); datacoll_->SetOwnData(true); } mfem::ParMesh& StateManager::mesh() { auto mesh = datacoll_->GetMesh(); SLIC_ERROR_ROOT_IF(!mesh, "The datastore does not contain a mesh object"); return static_cast<mfem::ParMesh&>(*mesh); } } // namespace serac
37.653465
117
0.694715
jamiebramwell
2274b38223ec0101805591c9d00f091faada64f5
148
cpp
C++
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
1
2021-07-25T15:54:27.000Z
2021-07-25T15:54:27.000Z
src/chess/tweenable.cpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
#include "tweenable.hpp" void Tweenable::update(float delta_time) { if (done()) { return; } m_t += delta_time / m_duration; }
13.454545
40
0.594595
delveam
22768f05debe929a3112e1e8c69e158092ec23f2
2,536
cpp
C++
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
null
null
null
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
null
null
null
Source/MapGenerator/Utils/MapEditorUtils.cpp
benoitestival/MapModuleEditor
3a7d72d0dc3761bd61f19df1e5af46081a791356
[ "MIT" ]
1
2021-07-07T09:22:28.000Z
2021-07-07T09:22:28.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "MapEditorUtils.h" #include "MapGenerator/GameMode/EditorGameMode.h" #include "MapGenerator/MapActor.h" #include "MapGenerator/Objects/BaseMapManager.h" #include "MapGenerator/HeightMapLandscape/LandscapeManager.h" #include "MapGenerator/Volumetric3DTerrain/Volumetric3DTerrainManager.h" #include "MapGenerator/HeightMapPlanet/HeightMapPlanetManager.h" TEnumAsByte<EMapType> UMapEditorUtils::DefaultMapType = EMapType::ProceduralLandscape; TEnumAsByte<EMapType> UMapEditorUtils::ActualMapType = UMapEditorUtils::DefaultMapType; TMap<EMapType, UClass*> UMapEditorUtils::ManagerRegistry = TMap<EMapType, UClass*>(); TMap<EMapType, FString> UMapEditorUtils::ModeName = TMap<EMapType, FString>(); bool UMapEditorUtils::IsRunning = false; void UMapEditorUtils::InitMapEditor() { ManagerRegistry.Empty();//Just in case ManagerRegistry.Add({EMapType::ProceduralLandscape}, {ULandscapeManager::StaticClass()}); ManagerRegistry.Add({EMapType::ProceduralHMPlanet}, {UHeightMapPlanetManager::StaticClass()}); ManagerRegistry.Add({EMapType::Volumetric3DLandscape}, {UVolumetric3DTerrainManager::StaticClass()}); ModeName.Add({ EMapType::ProceduralLandscape }, { "Landscape procedural" }); ModeName.Add({ EMapType::ProceduralHMPlanet }, { "HM Planet procedural" }); ModeName.Add({ EMapType::Volumetric3DLandscape }, { "Terrain Volumetric" }); IsRunning = true; UEditorGameMode::Get(); } void UMapEditorUtils::DestroyMapEditor() { UEditorGameMode::Destroy(); ManagerRegistry.Empty(); IsRunning = false; } bool UMapEditorUtils::IsEditorRunning() { return IsRunning; } AMapActor* UMapEditorUtils::GetMapActor() { return UMapEditorUtils::GetMapGameMode()->GetMapActor(); } UBaseMapManager* UMapEditorUtils::GetActualMapManager() { return UMapEditorUtils::GetMapActor()->MapManager; } ULandscapeManager* UMapEditorUtils::TryGetLandscapeManager() { return Cast<ULandscapeManager>(UMapEditorUtils::GetActualMapManager()); } UVolumetric3DTerrainManager* UMapEditorUtils::tryGetVolumetricTerrainManager() { return Cast<UVolumetric3DTerrainManager>(UMapEditorUtils::GetActualMapManager()); } UHeightMapPlanetManager * UMapEditorUtils::TryGetHeightMapPlanetManager() { return Cast<UHeightMapPlanetManager>(UMapEditorUtils::GetActualMapManager()); } UWorld* UMapEditorUtils::GetActualWorld() { return UMapEditorUtils::GetMapGameMode()->GetWorld(); } UEditorGameMode* UMapEditorUtils::GetMapGameMode() { return UEditorGameMode::Get(); }
35.71831
102
0.800473
benoitestival
22827a71da757c0d7d34edb96ca7818e35355799
2,849
hpp
C++
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
3
2017-11-01T21:47:57.000Z
2022-01-07T03:50:58.000Z
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
src/Magma/Window/GLFWWindow.hpp
RiscadoA/Magma-Engine
ebf8d8c25d631a9731efa33e23b162339985ae3b
[ "Zlib" ]
null
null
null
#pragma once #include "Window.hpp" #include <atomic> #include <queue> struct GLFWwindow; namespace Magma { /// <summary> /// Implements Window abstract interface class using GLFW /// </summary> class GLFWWindow : public Window { public: GLFWWindow(); virtual ~GLFWWindow() final; /// <summary> /// Gets this window GLFW handle /// </summary> /// <returns>This window GLFW handle</returns> inline GLFWwindow* GetGLFWWindow() { return m_glfwWindow; } /// <summary> /// Converts a GLFW mouse button to an Magma mouse button /// </summary> /// <param name="button">GLFW Mouse button to be converted</param> /// <returns>Corresponding Magma mouse button</returns> static Mouse::Button GLFWMButtonToMagma(int button); /// <summary> /// Converts a GLFW keyboard key to an Magma keyboard key /// </summary> /// <param name="key">GLFW keyboard ey to be converted</param> /// <returns>Corresponding Magma keyboard key</returns> static Keyboard::Key GLFWKeyToMagma(int key); protected: // Inherited via Window virtual bool DerivedIsOpen() final; virtual void DerivedOpen() final; virtual void DerivedClose() final; virtual void DerivedResize() final; virtual void DerivedSetTitle() final; virtual void DerivedSetMode() final; virtual void SetVSyncEnabled(bool vsyncEnabled) final; virtual bool DerivedPollEvent(Magma::UIEvent& event) final; virtual void DerivedDisplay() final; virtual glm::vec2 GetMousePosition() final; virtual void SetMousePosition(glm::vec2 mousePosition) final; virtual bool IsKeyboardKeyPressed(Keyboard::Key key) override; virtual bool IsMouseCursorVisible() override; virtual bool IsMouseButtonPressed(Mouse::Button button) override; virtual void SetMouseCursorVisible(bool visible) override; virtual void DerivedMakeActive() override; private: static void GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); static void GLFWMouseButtonCallback(GLFWwindow* window, int button, int action, int mods); static void GLFWMouseScrollCallback(GLFWwindow* window, double x, double y); static void GLFWCursorPosCallback(GLFWwindow* window, double xpos, double ypos); static void GLFWCursorEnterCallback(GLFWwindow* window, int entered); static void GLFWCharCallback(GLFWwindow* window, unsigned int codePoint); static void GLFWResizeCallback(GLFWwindow* window, int width, int height); static void GLFWFocusCallback(GLFWwindow* window, int focused); static void GLFWCloseCallback(GLFWwindow* window); static std::atomic<int> s_windowNumber; GLFWwindow* m_glfwWindow; bool m_mouseButtonStates[static_cast<size_t>(Mouse::Button::Count)]; bool m_keyboardKeyStates[static_cast<size_t>(Keyboard::Key::Count)]; bool m_mouseCursorVisible = true; std::queue<Magma::UIEvent> m_eventQueue; }; }
34.325301
95
0.75079
RiscadoA
22839d29257f3790c1872f3f32c065b3689ba351
3,320
cpp
C++
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/graphics/ctexturefontloader.cpp
dogtwelve/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#include <eepp/graphics/ctexturefontloader.hpp> #include <eepp/graphics/cfontmanager.hpp> namespace EE { namespace Graphics { cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const eeUint& StartChar, const eeUint& Spacing, const eeUint& TexColumns, const eeUint& TexRows, const Uint16& NumChars ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_TEX ), mFontName( FontName ), mStartChar( StartChar ), mSpacing( Spacing ), mTexColumns( TexColumns ), mTexRows( TexRows ), mNumChars( NumChars ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const std::string& CoordinatesDatPath ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_PATH ), mFontName( FontName ), mFilepath( CoordinatesDatPath ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, cPack * Pack, const std::string& FilePackPath ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_PACK ), mFontName( FontName ), mFilepath( FilePackPath ), mPack( Pack ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::cTextureFontLoader( const std::string FontName, cTextureLoader * TexLoader, const char* CoordData, const Uint32& CoordDataSize ) : cObjectLoader( FontTexLoader ), mLoadType( TEF_LT_MEM ), mFontName( FontName ), mData( CoordData ), mDataSize( CoordDataSize ), mTexLoaded( false ), mFontLoaded( false ) { mTexLoader = TexLoader; } cTextureFontLoader::~cTextureFontLoader() { eeSAFE_DELETE( mTexLoader ); } void cTextureFontLoader::Start() { cObjectLoader::Start(); mTexLoader->Threaded( false ); if ( !mThreaded ) { Update(); } } void cTextureFontLoader::Update() { if ( !mLoaded ) { if ( !mTexLoaded ) { mTexLoader->Load(); mTexLoader->Update(); mTexLoaded = mTexLoader->IsLoaded(); } if ( mTexLoaded && !mFontLoaded ) { LoadFont(); } if ( mFontLoaded ) { SetLoaded(); } } } const std::string& cTextureFontLoader::Id() const { return mFontName; } void cTextureFontLoader::LoadFromPath() { mFont->Load( mTexLoader->Id(), mFilepath ); } void cTextureFontLoader::LoadFromMemory() { mFont->LoadFromMemory( mTexLoader->Id(), mData, mDataSize ); } void cTextureFontLoader::LoadFromPack() { mFont->LoadFromPack( mTexLoader->Id(), mPack, mFilepath ); } void cTextureFontLoader::LoadFromTex() { mFont->Load( mTexLoader->Id(), mStartChar, mSpacing, mTexColumns, mTexRows, mNumChars ); } void cTextureFontLoader::LoadFont() { mFont = cTextureFont::New( mFontName ); if ( TEF_LT_PATH == mLoadType ) LoadFromPath(); else if ( TEF_LT_MEM == mLoadType ) LoadFromMemory(); else if ( TEF_LT_PACK == mLoadType ) LoadFromPack(); else if ( TEF_LT_TEX == mLoadType ) LoadFromTex(); mFontLoaded = true; } cFont * cTextureFontLoader::Font() const { return mFont; } void cTextureFontLoader::Unload() { if ( mLoaded ) { mTexLoader->Unload(); cFontManager::instance()->Remove( mFont ); Reset(); } } void cTextureFontLoader::Reset() { cObjectLoader::Reset(); mFont = NULL; mTexLoaded = false; mFontLoaded = false; } }}
22.432432
219
0.716566
dogtwelve
2285ef05a4bee2ac69dd0545677fe1b1304e5cdb
33,821
cpp
C++
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
tests/storeTests/TestHMStorageHostGroup.cpp
tkraiser/NetCHASM
6b6e70fb071c9be497b0f83359ecfa0ef6e8b2f4
[ "Apache-2.0" ]
null
null
null
// Copyright 2019, Oath Inc. // Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details. #include "TestHMStorageHostGroup.h" #include "common.h" #include "TestStorageHostGroup.h" using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION(TESTNAME); void TESTNAME::setUp() { setupCommon(); } void TESTNAME::tearDown() { teardownCommon(); } void TESTNAME::test_HMStorageHostGroup_ReadOnly() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress missingAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(true); // A store request should fail CPPUNIT_ASSERT(!storageHost->storeCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_2); // Missing entries CPPUNIT_ASSERT(!storageHost->getCheckResult("missing.hm.com", address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, missingAddress, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParamsMissing, testresult)); storageHost->closeStore(); delete storageHost; } void TESTNAME::test_HMStorageHostGroup_ReadWrite() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; dataHostGroup1.addHost(hostname1_1); dataHostGroup1.addHost(hostname1_2); dataHostGroup2.addHost(hostname2_1); dataHostGroup2.addHost(hostname2_2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress missingAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMDataCheckResult testresult; vector<HMGroupCheckResult> results; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->openStore(false); // A store request should fail CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, result1_1_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, result1_1_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, result1_2_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, result1_2_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, result2_1_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, result2_1_2)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, result2_2_1)); CPPUNIT_ASSERT(storageHost->storeCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, result2_2_2)); std::this_thread::sleep_for(10ms); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_1, address1_1_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname1_2, address1_2_2, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(testresult == result1_2_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_1, address2_1_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_1_2); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_1, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_1); CPPUNIT_ASSERT(storageHost->getCheckResult(hostname2_2, address2_2_2, hostCheck, checkParams2, testresult)); CPPUNIT_ASSERT(testresult == result2_2_2); storageHost->populateHostGroup(true); CPPUNIT_ASSERT(storageHost->getGroupCheckResults(hostGroup1, true, false ,results)); CPPUNIT_ASSERT_EQUAL(4, (int)results.size()); // Note in the multimap, we don't have any strong guarentee of the oredering bool entry1, entry2, entry3, entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname1_1) { if(it->m_address == address1_1_1) { CPPUNIT_ASSERT(it->m_result == result1_1_1); entry1 = true; } else if(it->m_address == address1_1_2) { CPPUNIT_ASSERT(it->m_result == result1_1_2); entry2 = true; } } else if(it->m_hostName == hostname1_2) { if(it->m_address == address1_2_1) { CPPUNIT_ASSERT(it->m_result == result1_2_1); entry3 = true; } else if(it->m_address == address1_2_2) { CPPUNIT_ASSERT(it->m_result == result1_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); CPPUNIT_ASSERT(storageHost->getGroupCheckResults(hostGroup2, true, false, results)); CPPUNIT_ASSERT(results.size() == 4); entry1 = entry2 = entry3 = entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); // Missing entries CPPUNIT_ASSERT(!storageHost->getCheckResult("missing.hm.com", address1_1_1, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, missingAddress, hostCheck, checkParams1, testresult)); CPPUNIT_ASSERT(!storageHost->getCheckResult(hostname1_1, address1_1_1, hostCheck, checkParamsMissing, testresult)); CPPUNIT_ASSERT(!storageHost->getGroupCheckResults("missingGroup",true, false, results)); storageHost->closeStore(); delete storageHost; } void TESTNAME::test_HMStorageHostGroup_Restore() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); dataHostGroup1.addHost(hostname1_1); dataHostGroup1.addHost(hostname1_2); dataHostGroup2.addHost(hostname2_1); dataHostGroup2.addHost(hostname2_2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); set<HMIPAddress> ips1_1; ips1_1.insert(address1_1_1); ips1_1.insert(address1_1_2); set<HMIPAddress> ips1_2; ips1_2.insert(address1_2_1); ips1_2.insert(address1_2_2); set<HMIPAddress> ips2_1; ips2_1.insert(address2_1_1); ips2_1.insert(address2_1_2); set<HMIPAddress> ips2_2; ips2_2.insert(address2_2_1); ips2_2.insert(address2_2_2); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); HMDataCheckList* checkList = new HMDataCheckList(); checkList->insertCheck(hostGroup1, hostname1_1, hostCheck, checkParams1, ips1_1); checkList->insertCheck(hostGroup1, hostname1_2, hostCheck, checkParams1, ips1_2); checkList->insertCheck(hostGroup2, hostname2_1, hostCheck, checkParams2, ips2_1); checkList->insertCheck(hostGroup2, hostname2_2, hostCheck, checkParams2, ips2_2); HMDNSCache* dnsCache = new HMDNSCache(); HMAuxCache auxCache; storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(false); storageHost->initResultsFromBackend(*checkList, *dnsCache, auxCache); set<HMIPAddress> vip_ret; CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address1_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_1_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_1) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_2) != vip_ret.end()); vip_ret.clear(); CPPUNIT_ASSERT(dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address2_2_2) != vip_ret.end());; std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> results; CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_1, hostCheck, address1_1_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_1_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_1, hostCheck, address1_1_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_1_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_2, hostCheck, address1_2_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_2_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname1_2, hostCheck, address1_2_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result1_2_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_1, hostCheck, address2_1_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_1_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_1, hostCheck, address2_1_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_1_2); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_2, hostCheck, address2_2_1, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_2_1); CPPUNIT_ASSERT(checkList->getCheckResults(hostname2_2, hostCheck, address2_2_2, results)); CPPUNIT_ASSERT(results.size() == 1); CPPUNIT_ASSERT(results[0].first == checkParams1); CPPUNIT_ASSERT(results[0].second == result2_2_2); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; // Test an empty hostGroup list HMDataHostGroupMap emptyHostGroupMap; storageHost = new TestStorageHostGroup(&emptyHostGroupMap); checkList = new HMDataCheckList(); dnsCache = new HMDNSCache(); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(false); // TODO fix the initResultsFromBackend //CPPUNIT_ASSERT(storageHost->restoreResults(*checkList, *dnsCache)); // Now nothing should be restored vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname1_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_1, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV4_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_IPV6_ONLY, vip_ret)); vip_ret.clear(); CPPUNIT_ASSERT(!dnsCache->getAddresses(hostname2_2, HM_DUALSTACK_BOTH, vip_ret)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_1, hostCheck, address1_1_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_1, hostCheck, address1_1_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_2, hostCheck, address1_2_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname1_2, hostCheck, address1_2_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_1, hostCheck, address2_1_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_1, hostCheck, address2_1_2, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_2, hostCheck, address2_2_1, results)); CPPUNIT_ASSERT(!checkList->getCheckResults(hostname2_2, hostCheck, address2_2_2, results)); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; storageHost = new TestStorageHostGroup(&hostGroupMap); checkList = new HMDataCheckList(); dnsCache = new HMDNSCache(); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); storageHost->openStore(true); // TODO fix initResultsFromBackend //CPPUNIT_ASSERT(!storageHost->restoreResults(*checkList, *dnsCache)); storageHost->closeStore(); delete storageHost; delete checkList; delete dnsCache; } void TESTNAME::test_HMStorageHostGroup_InternalFunctions() { HMDataHostGroupMap hostGroupMap; string hostGroup1 = "hostgroup1"; string hostGroup2 = "hostgroup2"; HMDataHostGroup dataHostGroup1(hostGroup1); HMDataHostGroup dataHostGroup2(hostGroup2); hostGroupMap.insert(make_pair(hostGroup1, dataHostGroup1)); hostGroupMap.insert(make_pair(hostGroup2, dataHostGroup2)); HMDataHostCheck hostCheck; HMDataCheckParams checkParams1; dataHostGroup1.getCheckParameters(checkParams1); checkParams1.addHostGroup(hostGroup1); HMDataCheckParams checkParams2; dataHostGroup1.getCheckParameters(checkParams2); checkParams2.addHostGroup(hostGroup2); HMDataCheckParams checkParamsMissing; string hostname1_1 = "test1_1.hm.com"; string hostname1_2 = "test1_2.hm.com"; string hostname2_1 = "test2_1.hm.com"; string hostname2_2 = "test2_2.hm.com"; HMIPAddress address1_1_1; HMIPAddress address1_1_2; HMIPAddress address1_2_1; HMIPAddress address1_2_2; HMIPAddress address2_1_1; HMIPAddress address2_1_2; HMIPAddress address2_2_1; HMIPAddress address2_2_2; HMIPAddress testAddress; address1_1_1.set("192.168.0.1"); address1_1_2.set("fad0::1"); address1_2_1.set("192.168.0.2"); address1_2_2.set("fad0::2"); address2_1_1.set("192.168.0.3"); address2_1_2.set("fad0::3"); address2_2_1.set("192.168.0.4"); address2_2_2.set("fad0::4"); HMDataCheckResult result1_1_1; HMDataCheckResult result1_1_2; HMDataCheckResult result1_2_1; HMDataCheckResult result1_2_2; HMDataCheckResult result2_1_1; HMDataCheckResult result2_1_2; HMDataCheckResult result2_2_1; HMDataCheckResult result2_2_2; result1_1_1.m_numChecks = 1; result1_1_2.m_numChecks = 2; result1_2_1.m_numChecks = 3; result1_2_2.m_numChecks = 4; result2_1_1.m_numChecks = 5; result2_1_2.m_numChecks = 6; result2_2_1.m_numChecks = 7; result2_2_2.m_numChecks = 8; HMGroupCheckUpdate update1(hostGroup1, hostname1_1, address1_1_1, result1_1_1); HMGroupCheckUpdate update2(hostGroup1, hostname1_1, address1_1_2, result1_1_2); HMGroupCheckUpdate update3(hostGroup1, hostname1_2, address1_2_1, result1_2_1); HMGroupCheckUpdate update4(hostGroup1, hostname1_2, address1_2_2, result1_2_2); HMGroupCheckUpdate update5(hostGroup2, hostname2_1, address2_1_1, result2_1_1); HMGroupCheckUpdate update6(hostGroup2, hostname2_1, address2_1_2, result2_1_2); HMGroupCheckUpdate update7(hostGroup2, hostname2_2, address2_2_1, result2_2_1); HMGroupCheckUpdate update8(hostGroup2, hostname2_2, address2_2_2, result2_2_2); HMDataCheckResult testresult; TestStorageHostGroup* storageHost = new TestStorageHostGroup(&hostGroupMap); storageHost->test_manual_add(update1); storageHost->test_manual_add(update2); storageHost->test_manual_add(update3); storageHost->test_manual_add(update4); storageHost->test_manual_add(update5); storageHost->test_manual_add(update6); storageHost->test_manual_add(update7); storageHost->test_manual_add(update8); std::vector<HMGroupCheckResult> results; HMDataHostGroup updateHostGroupTest1(hostGroup1); HMDataHostGroup updateHostGroupTest2(hostGroup2); const HMDataHostGroup* hostGroupTest1; const HMDataHostGroup* hostGroupTest2; string missingGroup = "missingGroup"; // Test retrieving group names CPPUNIT_ASSERT(!storageHost->test_getInternalHostGroupInfo(missingGroup, hostGroupTest1)); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupInfo(hostGroup1, hostGroupTest1)); CPPUNIT_ASSERT(hostGroupTest1->getName() == hostGroup1); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupInfo(hostGroup2, hostGroupTest2)); CPPUNIT_ASSERT(hostGroupTest2->getName() == hostGroup2); updateHostGroupTest1 = *hostGroupTest1; updateHostGroupTest2 = *hostGroupTest2; storageHost->populateHostGroup(false); // Test retrieving the health check results CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup1, results) == 4); CPPUNIT_ASSERT(results.size() == 4); bool entry1, entry2, entry3, entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname1_1) { if(it->m_address == address1_1_1) { CPPUNIT_ASSERT(it->m_result == result1_1_1); entry1 = true; } else if(it->m_address == address1_1_2) { CPPUNIT_ASSERT(it->m_result == result1_1_2); entry2 = true; } } else if(it->m_hostName == hostname1_2) { if(it->m_address == address1_2_1) { CPPUNIT_ASSERT(it->m_result == result1_2_1); entry3 = true; } else if(it->m_address == address1_2_2) { CPPUNIT_ASSERT(it->m_result == result1_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); // Check for missing health check results CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(missingGroup, results) == 0); CPPUNIT_ASSERT(results.size() == 0); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup2, results) == 4); CPPUNIT_ASSERT(results.size() == 4); entry1 = entry2 = entry3 = entry4 = false; for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); CPPUNIT_ASSERT(storageHost->test_getInternalHostGroupResults(hostGroup1, results) == 4); CPPUNIT_ASSERT(results.size() == 4); for(auto it = results.begin(); it != results.end(); ++it) { if(it->m_hostName == hostname2_1) { if(it->m_address == address2_1_1) { CPPUNIT_ASSERT(it->m_result == result2_1_1); entry1 = true; } else if(it->m_address == address2_1_2) { CPPUNIT_ASSERT(it->m_result == result2_1_2); entry2 = true; } } else if(it->m_hostName == hostname2_2) { if(it->m_address == address2_2_1) { CPPUNIT_ASSERT(it->m_result == result2_2_1); entry3 = true; } else if(it->m_address == address2_2_2) { CPPUNIT_ASSERT(it->m_result == result2_2_2); entry4 = true; } } } CPPUNIT_ASSERT(entry1 && entry2 && entry3 && entry4); delete storageHost; }
39.556725
126
0.717838
tkraiser
228770341eaf4887a11b131dce6cda60ad4e53fa
4,833
cpp
C++
src/nnfusion/core/graph/graph_util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/graph/graph_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/graph/graph_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "graph_util.hpp" #include <queue> void nnfusion::graph::ReverseDFS(const Graph* graph, const GNodeVector& start, const std::function<void(std::shared_ptr<GNode>)>& enter, const std::function<void(std::shared_ptr<GNode>)>& leave, const NodeComparator& stable_comparator) { // Stack of work to do. struct Work { std::shared_ptr<GNode> node; bool leave; // Are we entering or leaving node? }; std::vector<Work> stack(start.size()); for (int i = 0; i < start.size(); ++i) { stack[i] = Work{start[i], false}; } std::vector<bool> visited(graph->get_max_node_id(), false); while (!stack.empty()) { Work w = stack.back(); stack.pop_back(); std::shared_ptr<GNode> node = w.node; if (w.leave) { leave(node); continue; } if (visited[node->get_id()]) { continue; } visited[node->get_id()] = true; if (enter) { enter(node); } // Arrange to call leave(node) when all done with descendants. if (leave) { stack.push_back(Work{node, true}); } auto add_work = [&visited, &stack](std::shared_ptr<GNode> in_node) { if (!visited[in_node->get_id()]) { // Note; we must not mark as visited until we actually process it. stack.push_back(Work{in_node, false}); } }; if (stable_comparator) { GNodeVector in_nodes_sorted; for (auto in_edge : node->get_in_edges()) { in_nodes_sorted.emplace_back(in_edge->get_src()); } std::sort(in_nodes_sorted.begin(), in_nodes_sorted.end(), stable_comparator); for (auto in_node : in_nodes_sorted) { add_work(in_node); } } else { for (auto in_edge : node->get_in_edges()) { add_work(in_edge->get_src()); } } } } void nnfusion::graph::BFS(const Graph* graph, const GNodeVector& start, const std::function<void(std::shared_ptr<GNode>)>& enter, const std::function<void(std::shared_ptr<GNode>)>& leave, const NodeComparator& stable_comparator) { // Stack of work to do. struct Work { std::shared_ptr<GNode> node; bool leave; // Are we entering or leaving node? }; std::queue<Work> queue; for (int i = 0; i < start.size(); ++i) { queue.push(Work{start[i], false}); } std::vector<bool> visited(graph->get_max_node_id(), false); while (!queue.empty()) { Work w = queue.front(); queue.pop(); std::shared_ptr<GNode> node = w.node; if (w.leave) { leave(node); continue; } if (visited[node->get_id()]) { continue; } visited[node->get_id()] = true; if (enter) { enter(node); } if (leave) { queue.push(Work{node, true}); } auto add_work = [&visited, &queue](std::shared_ptr<GNode> out_node) { if (!visited[out_node->get_id()]) { // Note; we must not mark as visited until we actually process it. bool all_input_visited = true; for (auto& edge : out_node->get_in_edges()) { auto input_node = edge->get_src(); if (!visited[input_node->get_id()]) { all_input_visited = false; break; } } if (all_input_visited) queue.push(Work{out_node, false}); } }; if (stable_comparator) { GNodeVector out_nodes_sorted; for (auto out_edge : node->get_out_edges()) { out_nodes_sorted.emplace_back(out_edge->get_dst()); } std::sort(out_nodes_sorted.begin(), out_nodes_sorted.end(), stable_comparator); for (auto out_node : out_nodes_sorted) { add_work(out_node); } } else { for (auto out_edge : node->get_out_edges()) { add_work(out_edge->get_dst()); } } } }
28.263158
91
0.470515
lynex
22888136451d7d988fa8cc94016c41d942d399cf
2,720
cpp
C++
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
worker/src/Master/RtcMaster.cpp
idarkblue/mediasoup
f77bbd3680c122a2a4f15836b746e53e4b8571d0
[ "0BSD" ]
null
null
null
#define PMS_CLASS "pingos::RtcMaster" #define MS_CLASS "pingos::RtcMaster" #include "Master/Defines.hpp" #include "Master/RtcMaster.hpp" #include "Master/Log.hpp" #include "Master/RtcWorker.hpp" #include "MediaSoupErrors.hpp" namespace pingos { RtcMaster::RtcMaster() { } RtcMaster::~RtcMaster() { } RtcWorker* RtcMaster::FindWorker(std::string streamId) { size_t hashVal = std::hash<std::string>()(streamId); size_t slot = hashVal % this->GetWorkerCount(); return this->FindWorker(slot); } RtcSession* RtcMaster::CreateSession(std::string streamId, RtcSession::Role role) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("StreamId[{}], Worker not found", streamId); MS_THROW_ERROR("Worker not found"); return nullptr; } auto sessionId = this->SpellSessionId(); RtcSession *rtcSession = worker->CreateSession(streamId, sessionId, role); if (!rtcSession) { PMS_ERROR("SessionId[{}] StreamId[{}] create session failed.", sessionId, streamId); return nullptr; } PMS_INFO("SessionId[{}] StreamId[{}], RTC Session creation success, session ptr[{}].", sessionId, streamId, (void *)rtcSession); return rtcSession; } RtcWorker* RtcMaster::FindWorker(uint32_t slot) { auto it = m_slotWorkerMap.find(slot); if (it != m_slotWorkerMap.end()) { return (RtcWorker*) it->second; } return nullptr; } Worker* RtcMaster::NewWorker(uv_loop_t *loop) { return new RtcWorker(loop); } void RtcMaster::DeleteWorker(Worker *worker) { delete (RtcWorker*)worker; } std::string RtcMaster::SpellSessionId() { static uint64_t id = 0; std::string sessionId = std::string("sid") + std::to_string(id); id++; return sessionId; } RtcSession* RtcMaster::FindPublisher(std::string streamId) { auto worker = this->FindWorker(streamId); if (worker == nullptr) { return nullptr; } return worker->FindPublisher(streamId); } RtcSession* RtcMaster::FindSession(std::string streamId, std::string sessionId) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("SessionId[{}] StreamId[{}] Failed to find worker", sessionId, streamId); return nullptr; } return worker->FindSession(streamId, sessionId); } void RtcMaster::DeleteSession(std::string streamId, std::string sessionId) { auto worker = this->FindWorker(streamId); if (!worker) { PMS_ERROR("SessionId[{}] StreamId[{}], Worker not found", sessionId, streamId); return; } PMS_INFO("SessionId[{}] StreamId[{}], RTC Session deleted.", sessionId, streamId); worker->DeleteSession(streamId, sessionId); } }
22.666667
92
0.666912
idarkblue
228a1f7e09f9a0015524cf5801846fb76324f36d
1,097
cpp
C++
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
p_euler_102.cpp
Krshivam/Project-Euler
108d4c98450de09315e399956665edd369a50d64
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define pll pair<ll,ll> #define mp make_pair #define pb push_back ll dist(pll a,pll b){ return sqrt((a.first-b.first)*(a.first-b.first) + (a.second-b.second)*(a.second-b.second)); } ll area(ll a,ll b, ll c){ ll s = (a+b+c); return (s)*(a+b-c)*(a+c-b)*(b+c-a); } ll area1(pll a,pll b,pll c){ return abs((a.first*(b.second-c.second)+b.first*(c.second-a.second)+c.first*(a.second-b.second))); } int main(int argc, char const *argv[]) { int n = 1000; int cnt=0; while(n--){ string s; getline(cin,s); pll x,y,z; std::vector<ll> v; stringstream ss(s); for(int i;ss>>i;){ v.pb(i); if(ss.peek() == ','){ ss.ignore(); } } //cout<<v.size()<<" "; //int cnt=0; x.first = v[0]; x.second = v[1]; y.first = v[2]; y.second = v[3]; z.first = v[4]; z.second = v[5]; //cout<<x.first<<" "; pll o = mp(0LL,0LL); cout<<area1(x,y,z)<<endl; if(area1(x,y,z)==area1(x,y,o)+area1(x,z,o)+area1(y,z,o)) cnt++; } cout<<cnt; return 0; }
19.245614
100
0.534184
Krshivam
228c325c39695039d7ee268d2b8eec42e2962d24
6,775
cpp
C++
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
source/examples/ex20_scene_graphs.cpp
3a2l/OpenGL-Examples
a7284a0fc596898188f53671dac36ae60da62408
[ "MIT" ]
null
null
null
#include <application.hpp> #include <shader.hpp> #include <imgui-utils/utils.hpp> #include <mesh/mesh.hpp> #include <mesh/mesh-utils.hpp> #include <camera/camera.hpp> #include <camera/controllers/fly_camera_controller.hpp> #include <glm/gtx/euler_angles.hpp> #include <json/json.hpp> #include <fstream> #include <string> #include <unordered_map> #include <optional> namespace glm { template<length_t L, typename T, qualifier Q> void from_json(const nlohmann::json& j, vec<L, T, Q>& v){ for(length_t index = 0; index < L; ++index) v[index] = j[index].get<T>(); } } struct Transform { glm::vec4 tint; glm::vec3 translation, rotation, scale; std::optional<std::string> mesh; std::unordered_map<std::string, std::shared_ptr<Transform>> children; Transform( const glm::vec4& tint = {1,1,1,1}, const glm::vec3& translation = {0,0,0}, const glm::vec3& rotation = {0,0,0}, const glm::vec3& scale = {1,1,1}, const std::optional<std::string>& mesh = std::nullopt ): tint(tint), translation(translation), rotation(rotation), scale(scale), mesh(mesh) {} [[nodiscard]] glm::mat4 to_mat4() const { return glm::translate(glm::mat4(1.0f), translation) * glm::yawPitchRoll(rotation.y, rotation.x, rotation.z) * glm::scale(glm::mat4(1.0f), scale); } }; class SceneGraphApplication : public our::Application { our::ShaderProgram program; std::unordered_map<std::string, std::unique_ptr<our::Mesh>> meshes; std::unordered_map<std::string, std::shared_ptr<Transform>> roots; std::string current_root_name; our::Camera camera; our::FlyCameraController controller; our::WindowConfiguration getWindowConfiguration() override { return { "Scene Graphs", {1280, 720}, false }; } void onInitialize() override { program.create(); program.attach("assets/shaders/ex11_transformation/transform.vert", GL_VERTEX_SHADER); program.attach("assets/shaders/ex11_transformation/tint.frag", GL_FRAGMENT_SHADER); program.link(); meshes["cube"] = std::make_unique<our::Mesh>(); our::mesh_utils::Cuboid(*(meshes["cube"]), true); meshes["rod"] = std::make_unique<our::Mesh>(); our::mesh_utils::Cuboid(*(meshes["rod"]), true, {0, 0, 0.5}); meshes["sphere"] = std::make_unique<our::Mesh>(); our::mesh_utils::Sphere(*(meshes["sphere"]), {32, 16}, true); int width, height; glfwGetFramebufferSize(window, &width, &height); camera.setEyePosition({10, 10, 10}); camera.setTarget({0, 0, 0}); camera.setUp({0, 1, 0}); camera.setupPerspective(glm::pi<float>()/2, static_cast<float>(width)/height, 0.1f, 100.0f); controller.initialize(this, &camera); roots["simple"] = loadSceneGraph("assets/data/ex20_scene_graphs/simple.json"); roots["solar-system"] = loadSceneGraph("assets/data/ex20_scene_graphs/solar-system.json"); roots["human"] = loadSceneGraph("assets/data/ex20_scene_graphs/human.json"); current_root_name = "simple"; glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); glClearColor(0, 0, 0, 1); } std::shared_ptr<Transform> loadNode(const nlohmann::json& json){ auto node = std::make_shared<Transform>( json.value<glm::vec4>("tint", {1,1,1,1}), json.value<glm::vec3>("translation", {0, 0, 0}), json.value<glm::vec3>("rotation", {0, 0, 0}), json.value<glm::vec3>("scale", {1, 1, 1}) ); if(json.contains("mesh")){ node->mesh = json["mesh"].get<std::string>(); } if(json.contains("children")){ for(auto& [name, child]: json["children"].items()){ node->children[name] = loadNode(child); } } return node; } std::shared_ptr<Transform> loadSceneGraph(const std::string& scene_file){ std::ifstream file_in(scene_file); nlohmann::json json; file_in >> json; file_in.close(); return loadNode(json); } void drawNode(const std::shared_ptr<Transform>& node, const glm::mat4& parent_transform_matrix){ glm::mat4 transform_matrix = parent_transform_matrix * node->to_mat4(); if(node->mesh.has_value()){ auto it = meshes.find(node->mesh.value()); if(it != meshes.end()) { program.set("tint", node->tint); program.set("transform", transform_matrix); it->second->draw(); } } for(auto& [name, child]: node->children){ drawNode(child, transform_matrix); } } void onDraw(double deltaTime) override { controller.update(deltaTime); glUseProgram(program); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawNode(roots[current_root_name], camera.getVPMatrix()); } void onDestroy() override { program.destroy(); for(auto& [name, mesh] : meshes){ mesh->destroy(); } meshes.clear(); } void displayNodeGui(const std::shared_ptr<Transform>& node, const std::string& node_name){ if(ImGui::TreeNode(node_name.c_str())){ if(node->mesh.has_value()) { our::PairIteratorCombo("Mesh", node->mesh.value(), meshes.begin(), meshes.end()); ImGui::ColorEdit4("Tint", glm::value_ptr(node->tint)); } ImGui::DragFloat3("Translation", glm::value_ptr(node->translation), 0.1f); ImGui::DragFloat3("Rotation", glm::value_ptr(node->rotation), 0.01f); ImGui::DragFloat3("Scale", glm::value_ptr(node->scale), 0.1f); for(auto& [name, child]: node->children){ displayNodeGui(child, name); } ImGui::TreePop(); } } void onImmediateGui(ImGuiIO &io) override { ImGui::Begin("Scene Graph"); if(ImGui::BeginCombo("Scene", current_root_name.c_str())){ for(auto& [name, root] : roots){ bool selected = current_root_name == name; if(ImGui::Selectable(name.c_str(), selected)) current_root_name = name; if(selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } displayNodeGui(roots[current_root_name], current_root_name); ImGui::End(); } }; int main(int argc, char** argv) { return SceneGraphApplication().run(); }
33.539604
108
0.586863
3a2l
229ab0e7949131966932572a17990d829807197d
8,714
cpp
C++
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/QuestScripts/Quest_UnGoro.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" /*--------------------------------------------------------------------------------------------------------*/ class RingoDeadNPC : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(RingoDeadNPC); RingoDeadNPC(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnLoad() { _unit->SetStandState(7); _unit->setDeathState(CORPSE); _unit->GetAIInterface()->m_canMove = false; } }; /*--------------------------------------------------------------------------------------------------------*/ // The Northern Pylon class NorthernPylon : public GameObjectAIScript { public: NorthernPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new NorthernPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4285); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ // The Eastern Pylon class EasternPylon : public GameObjectAIScript { public: EasternPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new EasternPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4287); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ //The Western Pylon class WesternPylon : public GameObjectAIScript { public: WesternPylon(GameObject* goinstance) : GameObjectAIScript(goinstance) {} static GameObjectAIScript* Create(GameObject* GO) { return new WesternPylon(GO); } void OnActivate(Player* pPlayer) { if(pPlayer->HasFinishedQuest(4284)) { QuestLogEntry* en = pPlayer->GetQuestLogForEntry(4288); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { uint32 newcount = en->GetMobCount(0) + 1; en->SetMobCount(0, newcount); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); return; } } else if(pPlayer->HasFinishedQuest(4284) == false) { pPlayer->BroadcastMessage("You need to have completed the quest : Crystals of Power"); } } }; /*--------------------------------------------------------------------------------------------------------*/ class ChasingAMe01 : public QuestScript { public: void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry) { float SSX = mTarget->GetPositionX(); float SSY = mTarget->GetPositionY(); float SSZ = mTarget->GetPositionZ(); Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 9623); if(creat == NULL) return; creat->m_escorter = mTarget; creat->GetAIInterface()->setMoveType(11); creat->GetAIInterface()->StopMovement(3000); creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "He-l-p Me... ts.. ts..."); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); sEAS.CreateCustomWaypointMap(creat); sEAS.WaypointCreate(creat, -6305.657715f, -1977.757080f, -268.076447f, 5.564124f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6292.354492f, -1988.233032f, -265.271667f, 4.821922f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6296.333984f, -2004.225342f, -268.766388f, 3.337522f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6329.421387f, -2007.737549f, -258.587250f, 3.769490f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6343.778809f, -2017.559204f, -256.952026f, 3.577064f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6360.504883f, -2030.157959f, -261.204926f, 3.526014f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6381.367676f, -2038.451904f, -262.319946f, 2.713128f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6404.608398f, -2028.813721f, -262.817230f, 1.146257f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6399.632813f, -2018.668091f, -263.569824f, 0.800682f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6383.180664f, -2003.231689f, -270.639984f, 0.631821f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6351.983887f, -1976.397827f, -276.039001f, 1.138403f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6342.651855f, -1958.451050f, -274.056122f, 1.805992f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6353.083008f, -1918.406006f, -264.135101f, 1.515395f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6350.737305f, -1900.465942f, -258.695831f, 2.677785f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6366.535645f, -1892.092651f, -256.424347f, 2.025904f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6378.548828f, -1866.535278f, -260.363281f, 1.154112f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6370.422852f, -1842.526978f, -259.409515f, 1.711744f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6374.264648f, -1825.782349f, -260.584442f, 1.955218f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6382.359375f, -1811.540527f, -266.374359f, 2.901623f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6383.307129f, -1794.137207f, -267.334686f, 1.821700f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6399.292980f, -1710.144897f, -273.734283f, 1.252285f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6361.579102f, -1582.413574f, -272.221008f, 1.798137f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6391.618652f, -1409.568237f, -272.190521f, 1.711742f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6407.588867f, -1305.676880f, -271.632935f, 0.553279f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6349.980469f, -1276.069580f, -266.971375f, 1.236575f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6324.551758f, -1233.252441f, -267.178619f, 0.451176f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6288.604492f, -1215.046265f, -267.426117f, 2.177482f, 1, 256, 8841); sEAS.WaypointCreate(creat, -6298.290039f, -1182.650024f, -269.101013f, 3.211410f, 1, 256, 8841); sEAS.EnableWaypoints(creat); } }; class A_Me01 : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(A_Me01); A_Me01(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnReachWP(uint32 iWaypointId, bool bForwards) { if(iWaypointId == 28) { _unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Tr.........."); _unit->Despawn(5000, 1000); sEAS.DeleteWaypoints(_unit); if(_unit->m_escorter == NULL) return; Player* plr = _unit->m_escorter; _unit->m_escorter = NULL; plr->GetQuestLogForEntry(4245)->SendQuestComplete(); } } }; void SetupUnGoro(ScriptMgr* mgr) { mgr->register_creature_script(9999, &RingoDeadNPC::Create); mgr->register_gameobject_script(164955, &NorthernPylon::Create); mgr->register_gameobject_script(164957, &EasternPylon::Create); mgr->register_gameobject_script(164956, &WesternPylon::Create); /*mgr->register_quest_script(4245, new ChasingAMe01());*/ mgr->register_creature_script(9623, &A_Me01::Create); }
38.728889
108
0.660431
499453466
229acf34e1869f8476a505292837124d6e7d76a8
336
cpp
C++
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1487/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int get_cnt_skip(int n, int k) { if (n % 2 == 0) { return 0; } return k / ((n - 1) / 2); } void solve() { int n, k; scanf("%d%d", &n, &k); printf("%d\n", (k - 1 + get_cnt_skip(n, k - 1)) % n + 1); } int main() { int t; scanf("%d", &t); while (t--) { solve(); } }
13.44
59
0.464286
vladshablinsky
22a08cf80db06465c549cf747068f85c5fde7287
896
hpp
C++
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
1
2020-10-11T06:54:04.000Z
2020-10-11T06:54:04.000Z
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
src/sdk/rules/LimitedTupleTrimmer.hpp
psettle/sudoku
ea0040f3a9c1c093fa9ece851d2ec4104760e97a
[ "MIT" ]
null
null
null
/** * LimitedTupleTrimmer.hpp - Limited Tuple Trimmer * * Check for limited tuples that have been resolved and delete them. */ #ifndef _SDK_LIMITEDTUPLETRIMMER #define _SDK_LIMITEDTUPLETRIMMER #include "sdk/data/LimitedTupleDatabase.hpp" #include "sdk/interfaces/ILimitedTupleObserver.hpp" #include "sdk/interfaces/IRule.hpp" namespace sdk { namespace rules { class LimitedTupleTrimmer : public interfaces::IRule { public: virtual ~LimitedTupleTrimmer() {} LimitedTupleTrimmer(data::LimitedTupleDatabase* database); void SetObserver(interfaces::ILimitedTupleObserver* observer); bool Apply() override; private: void SendProgress(data::LimitedTuple const& tuple, data::Cell const& breaking_member) const; data::LimitedTupleDatabase* database_; interfaces::ILimitedTupleObserver* observer_; }; } // namespace rules } // namespace sdk #endif /* _SDK_LIMITEDTUPLETRIMMER */
28.903226
94
0.780134
psettle
22a6c28912f0c699bf66157eefc0977754af59f6
2,231
cpp
C++
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
147
2017-10-05T01:42:02.000Z
2022-01-21T08:15:05.000Z
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
20
2018-05-17T01:55:16.000Z
2021-04-20T07:27:00.000Z
src/HttpCacheMetadata.cpp
commshare/easyhttpcpp
757ec75679c1cbc5f04c81a30133f4bcd3e780f4
[ "MIT" ]
32
2018-05-05T13:04:34.000Z
2022-03-25T16:57:11.000Z
/* * Copyright 2017 Sony Corporation */ #include "HttpCacheMetadata.h" namespace easyhttpcpp { HttpCacheMetadata::HttpCacheMetadata() : m_httpMethod(Request::HttpMethodGet), m_statusCode(-1), m_responseBodySize(0), m_sentRequestAtEpoch(0), m_receivedResponseAtEpoch(0), m_createdAtEpoch(0) { } HttpCacheMetadata::~HttpCacheMetadata() { } void HttpCacheMetadata::setUrl(const std::string& url) { m_url = url; } const std::string& HttpCacheMetadata::getUrl() const { return m_url; } void HttpCacheMetadata::setHttpMethod(Request::HttpMethod httpMethod) { m_httpMethod = httpMethod; } Request::HttpMethod HttpCacheMetadata::getHttpMethod() const { return m_httpMethod; } void HttpCacheMetadata::setStatusCode(int statusCode) { m_statusCode = statusCode; } int HttpCacheMetadata::getStatusCode() const { return m_statusCode; } void HttpCacheMetadata::setStatusMessage(const std::string& statusMessage) { m_statusMessage = statusMessage; } const std::string& HttpCacheMetadata::getStatusMessage() const { return m_statusMessage; } void HttpCacheMetadata::setResponseHeaders(Headers::Ptr pResponseHeaders) { m_pResponseHeaders = pResponseHeaders; } Headers::Ptr HttpCacheMetadata::getResponseHeaders() const { return m_pResponseHeaders; } void HttpCacheMetadata::setResponseBodySize(size_t responseBodySize) { m_responseBodySize = responseBodySize; } size_t HttpCacheMetadata::getResponseBodySize() const { return m_responseBodySize; } void HttpCacheMetadata::setSentRequestAtEpoch(std::time_t sentRequestAtEpoch) { m_sentRequestAtEpoch = sentRequestAtEpoch; } std::time_t HttpCacheMetadata::getSentRequestAtEpoch() const { return m_sentRequestAtEpoch; } void HttpCacheMetadata::setReceivedResponseAtEpoch(std::time_t receivedResponseAtEpoch) { m_receivedResponseAtEpoch = receivedResponseAtEpoch; } std::time_t HttpCacheMetadata::getReceivedResponseAtEpoch() const { return m_receivedResponseAtEpoch; } void HttpCacheMetadata::setCreatedAtEpoch(std::time_t createdAtEpoch) { m_createdAtEpoch = createdAtEpoch; } std::time_t HttpCacheMetadata::getCreatedAtEpoch() const { return m_createdAtEpoch; } } /* namespace easyhttpcpp */
19.919643
119
0.779023
commshare
22a7a56ac931e31adf1102ab56942347c6f443b4
5,938
cpp
C++
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
139
2017-10-30T13:19:56.000Z
2022-03-27T05:43:17.000Z
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
273
2018-03-05T13:09:48.000Z
2022-03-30T11:44:06.000Z
es-core/src/TextToSpeech.cpp
brooksytech/emulationstation
67f12cb26127ff4f46966ea3735308ee4fd4e1ed
[ "Apache-2.0", "MIT" ]
193
2017-10-29T18:59:54.000Z
2022-03-27T16:15:58.000Z
#include "TextToSpeech.h" #include "Log.h" #include "LocaleES.h" #if WIN32 #include "SystemConf.h" #include <sapi.h> #include <sphelper.h> #include <thread> #pragma comment(lib, "sapi.lib") void TextToSpeech::SpeakThread() { if (FAILED(::CoInitializeEx(NULL, COINITBASE_MULTITHREADED))) return; ISpVoice* pVoice = NULL; HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice); if (!SUCCEEDED(hr)) return; m_isAvailable = true; while (true) { std::unique_lock<std::mutex> lock(mMutex); mEvent.wait(lock, [this]() { return mShouldTerminate || !mSpeechQueue.empty(); }); if (mShouldTerminate) break; SpeakItem* item = nullptr; if (!mSpeechQueue.empty()) { item = mSpeechQueue.front(); mSpeechQueue.pop_front(); } lock.unlock(); if (item != nullptr) { pVoice->Speak(Utils::String::convertToWideString(item->text).c_str(), SPF_ASYNC | SPF_IS_XML | (item->expand ? 0 : SPF_PURGEBEFORESPEAK), NULL); delete item; } } pVoice->Pause(); pVoice->Release(); } #elif defined(_ENABLE_TTS_) #include <espeak/speak_lib.h> #endif std::weak_ptr<TextToSpeech> TextToSpeech::sInstance; TextToSpeech::TextToSpeech() { m_isAvailable = false; m_enabled = false; init(); } TextToSpeech::~TextToSpeech() { deinit(); } std::shared_ptr<TextToSpeech> & TextToSpeech::getInstance() { //check if an TextToSpeech instance is already created, if not create one static std::shared_ptr<TextToSpeech> sharedInstance = sInstance.lock(); if (sharedInstance == nullptr) { sharedInstance.reset(new TextToSpeech); sInstance = sharedInstance; } return sharedInstance; } void TextToSpeech::init() { if (m_isAvailable) return; #if WIN32 m_isAvailable = false; mShouldTerminate = false; mSpeakThread = new std::thread(&TextToSpeech::SpeakThread, this); #elif defined(_ENABLE_TTS_) m_isAvailable = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 0, NULL, 0) != EE_INTERNAL_ERROR; if (!m_isAvailable) return; char* envv = getenv("LANGUAGE"); if (envv != nullptr && std::string(envv).length() >= 4) setLanguage(envv); else { envv = getenv("LANG"); if (envv != nullptr && std::string(envv).length() >= 4) setLanguage(envv); } #endif } void TextToSpeech::deinit() { if (!m_isAvailable) return; m_isAvailable = false; m_enabled = false; #if WIN32 if (mSpeakThread != nullptr) { mShouldTerminate = true; mEvent.notify_all(); mSpeakThread->join(); delete mSpeakThread; mSpeakThread = nullptr; } #elif defined(_ENABLE_TTS_) if (espeak_Terminate() != EE_OK) { LOG(LogError) << "TTS::deinit() - Failed to terminate"; } #endif } bool TextToSpeech::isAvailable() { return m_isAvailable; } bool TextToSpeech::isEnabled() { return m_enabled; } void TextToSpeech::enable(bool v, bool playSay) { if (v == m_enabled) return; if (m_isAvailable && playSay) { m_enabled = true; // Force say(v ? _("SCREEN READER ENABLED") : _("SCREEN READER DISABLED")); } m_enabled = v; } bool TextToSpeech::toogle() { enable(!m_enabled); return m_enabled; } void TextToSpeech::setLanguage(const std::string language) { if (m_isAvailable == false) return; #ifdef _ENABLE_TTS_ std::string voice = "default"; std::string language_part1 = language.substr(0, 5); // espeak --voices //if(language_part1 == "ar_YE") voice = ""; if (language_part1 == "ca_ES") voice = "catalan"; if (language_part1 == "cy_GB") voice = "welsh"; if (language_part1 == "de_DE") voice = "german"; if (language_part1 == "el_GR") voice = "greek"; if (language_part1 == "es_ES") voice = "spanish"; if (language_part1 == "es_MX") voice = "spanish-latin-am"; //if(language_part1 == "eu_ES") voice = ""; if (language_part1 == "fr_FR") voice = "french"; if (language_part1 == "hu_HU") voice = "hungarian"; if (language_part1 == "it_IT") voice = "italian"; //if(language_part1 == "ja_JP") voice = ""; //if(language_part1 == "ko_KR") voice = ""; if (language_part1 == "nb_NO") voice = "norwegian"; if (language_part1 == "nl_NL") voice = "dutch"; if (language_part1 == "nn_NO") voice = "norwegian"; //if(language_part1 == "oc_FR") voice = ""; if (language_part1 == "pl_PL") voice = "polish"; if (language_part1 == "pt_BR") voice = "brazil"; if (language_part1 == "pt_PT") voice = "portugal"; if (language_part1 == "ru_RU") voice = "russian"; if (language_part1 == "sv_SE") voice = "swedish"; if (language_part1 == "tr_TR") voice = "turkish"; //if(language_part1 == "uk_UA") voice = ""; if (language_part1 == "zh_CN") voice = "Mandarin"; // or cantonese ? if (language_part1 == "zh_TW") voice = "Mandarin"; // or cantonese ? if (espeak_SetVoiceByName(voice.c_str()) == EE_OK) { LOG(LogInfo) << "TTS::setLanguage() - set to " << language_part1 << " (" << voice << ")"; } else { LOG(LogError) << "TTS::setLanguage() - Failed with " << language_part1 << " (" << voice << ")"; } #endif } void TextToSpeech::say(const std::string text, bool expand, const std::string lang) { if (!m_isAvailable || !m_enabled || text.empty()) return; #if WIN32 std::string language = lang; if (language.empty()) language = SystemConf::getInstance()->get("system.language"); if (language.empty() || language == "en") language = "en-US"; std::string full = "<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='" + language + "'>" + text + "</speak>"; std::unique_lock<std::mutex> lock(mMutex); if (!expand) mSpeechQueue.clear(); SpeakItem* item = new SpeakItem(); item->text = full; item->expand = expand; mSpeechQueue.push_back(item); mEvent.notify_one(); #elif defined(_ENABLE_TTS_) if (expand == false && espeak_IsPlaying() == 1) espeak_Cancel(); if (espeak_Synth(text.c_str(), text.length() * 4 /* potentially 4 bytes by char */, 0, POS_CHARACTER, 0, espeakCHARS_UTF8, NULL, NULL) != EE_OK) { LOG(LogError) << "TTS::say() - Failed"; } #endif }
23.105058
147
0.664534
brooksytech
22ad28df7094ac0534375bb2bcb3b6c19876399d
139
cpp
C++
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
2
2021-04-07T11:39:24.000Z
2022-03-02T11:24:58.000Z
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
null
null
null
ByteCat/src/byteCat/lua/LuaFunction.cpp
CodingWithMenno/ByteCat
0fd19aa6781a5c28c6ff5e6f66c9624ace860de7
[ "Apache-2.0" ]
null
null
null
#include "bcpch.h" #include "byteCat/lua/LuaFunction.h" namespace BC { void LuaAPI::LOG(std::string string) { LOG_ERROR(string); } }
12.636364
37
0.690647
CodingWithMenno
22b32ed752e2ce78c767cb3c241707c2c2cd6c19
3,063
cpp
C++
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
cobs/file/ranfold_index_header.cpp
karasikov/cobs
63ba36f042c59e14f721018e68e36e20a8bf4936
[ "MIT" ]
null
null
null
/******************************************************************************* * cobs/file/ranfold_index_header.cpp * * Copyright (c) 2018 Florian Gauger * Copyright (c) 2018 Timo Bingmann * * All rights reserved. Published under the MIT License in the LICENSE file. ******************************************************************************/ #include <cobs/file/ranfold_index_header.hpp> #include <cobs/util/file.hpp> namespace cobs { const std::string RanfoldIndexHeader::magic_word = "RANFOLD_INDEX"; const uint32_t RanfoldIndexHeader::version = 1; const std::string RanfoldIndexHeader::file_extension = ".rfd_idx.cobs"; void RanfoldIndexHeader::serialize(std::ofstream& ofs) const { serialize_magic_begin(ofs, magic_word, version); stream_put(ofs, m_term_space, m_term_hashes, m_doc_space_bytes, m_doc_hashes, (uint32_t)m_file_names.size(), (uint32_t)m_doc_array.size()); for (const auto& file_name : m_file_names) { ofs << file_name << std::endl; } // for (const auto& d : m_doc_array) { // cobs::serialize(ofs, d); // } serialize_magic_begin(ofs, magic_word, version); } void RanfoldIndexHeader::deserialize(std::ifstream& ifs) { deserialize_magic_begin(ifs, magic_word, version); uint32_t file_names_size, doc_array_size; stream_get(ifs, m_term_space, m_term_hashes, m_doc_space_bytes, m_doc_hashes, file_names_size, doc_array_size); m_file_names.resize(file_names_size); for (auto& file_name : m_file_names) { std::getline(ifs, file_name); } m_doc_array.resize(doc_array_size); for (auto& d : m_doc_array) { stream_get(ifs, d); } deserialize_magic_end(ifs, magic_word); } void RanfoldIndexHeader::write_file(std::ofstream& ofs, const std::vector<uint8_t>& data) { ofs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); serialize(ofs); ofs.write(reinterpret_cast<const char*>(data.data()), data.size()); } void RanfoldIndexHeader::write_file(const fs::path& p, const std::vector<uint8_t>& data) { if (!p.parent_path().empty()) fs::create_directories(p.parent_path()); std::ofstream ofs(p.string(), std::ios::out | std::ios::binary); write_file(ofs, data); } void RanfoldIndexHeader::read_file(std::ifstream& ifs, std::vector<uint8_t>& data) { ifs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit); deserialize(ifs); size_t size = get_stream_size(ifs); data.resize(size); ifs.read(reinterpret_cast<char*>(data.data()), size); } void RanfoldIndexHeader::read_file(const fs::path& p, std::vector<uint8_t>& data) { std::ifstream ifs(p.string(), std::ios::in | std::ios::binary); read_file(ifs, data); } } // namespace cobs /******************************************************************************/
34.41573
80
0.592556
karasikov
22b636954ca7a11b897fd7d86ea09522e79bd331
775
cpp
C++
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
competitive-programming/codeforces/#786-Div. 3/abc_sort.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; struct Node { int data; Node *next = NULL; }; void insertAtMiddle(Node **head, int data,int position) { int count = 0; while (count < position) { head = head->next; count++; } struct Node *newNode = new Node(); newNode->data = data; newNode-> next = head -> next -> next; head -> next = newNode; } bool isArrSorted(vector<int> arr, int n) { if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) if (arr[i - 1] > arr[i]) return false; return true; } vector<int> handleInsert(vector<int> arr){ int mid = (arr.size() - 1)/2; arr } string solve(stack<int> arr) { return } int main() { return 0; }
14.903846
56
0.529032
dushimsam
22b7846ef3357e993329c3b5eb37391160222741
1,805
cpp
C++
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/15-QPainter3/widget.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } //当鼠标按下时: 创建一条新线压入vector。并且将当前鼠标位置作为新线的起点。 void Widget::mousePressEvent(QMouseEvent *event){ QVector<QPoint>line; _lines.append(line); QVector<QPoint>&last_line = _lines.last(); //注意:引用而不是新建,否则不是同一个内存 last_line.append(event->pos()); update(); //注意一定要记得update } //如果鼠标正在移动:将这些移动的点都压入最上面也就是最新的线 #include <QDebug> void Widget::mouseMoveEvent(QMouseEvent *event){ // qDebug() << "mouseMoveEvent"; if(!_lines.size()){ //保证安全 QVector<QPoint>line; _lines.append(line); } QVector<QPoint>&last_line = _lines.last(); last_line.append(event->pos()); update(); //注意一定要记得update } //如果鼠标松开,这个点就是新线的终点,只需要把此时的点压入最新线就可以了 void Widget::mouseReleaseEvent(QMouseEvent *event){ QVector<QPoint>&last_line = _lines.last(); last_line.append(event->pos()); update(); //注意一定要记得update } //在鼠标事件中记录线的轨迹,在绘画事件中绘制轨迹 void Widget::paintEvent(QPaintEvent *event){ //创建画笔 // QPainter painter(this); //vector数组中有几条线 // for(int i = 0; i < _lines.size(); ++i){ //一条条绘制 // QVector<QPoint>line = _lines.at(i); // for(int j = 0; j < line.size(); ++j){ // QPoint tj = line.at(j); // painter.drawPoint(tj); //不要画点,画线有专门的函数 // } // } QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true);//反走样 painter.setPen(QPen(QColor(0, 255, 0), 3));// 设置画笔颜色、宽度 for(int i=0; i<_lines.size(); ++i) { const QVector<QPoint>& line = _lines.at(i); for(int j=0; j<line.size()-1; ++j) { painter.drawLine(line.at(j), line.at(j+1)); } } }
25.069444
70
0.610526
liukai-tech
42ef587ad8c653cd5c9abdcc52b28aa8fbd0583b
7,253
hpp
C++
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/loss_functions/mean_square_error_loss.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "math/metrics/mean_square_error.hpp" #include "ml/ops/ops.hpp" #include <cassert> #include <memory> #include <vector> namespace fetch { namespace ml { namespace ops { template <class T> class MeanSquareErrorLoss : public Ops<T> { public: using ArrayType = T; using DataType = typename ArrayType::Type; using SizeType = typename ArrayType::SizeType; using VecTensorType = typename Ops<T>::VecTensorType; explicit MeanSquareErrorLoss(ArrayType const &weightings = ArrayType()) : weightings_(weightings) {} ~MeanSquareErrorLoss() override = default; void Forward(VecTensorType const &inputs, ArrayType &output) override { assert(inputs.size() == 2); assert(inputs.at(0)->shape() == inputs.at(1)->shape()); if (weightings_.size() == static_cast<SizeType>(0)) { output(0, 0) = fetch::math::MeanSquareError((*inputs.at(0)), (*inputs.at(1))); } // rescale according to weights else { SizeType data_size = inputs.at(0)->shape(inputs.at(0)->shape().size() - 1); auto it1 = inputs.at(0)->cbegin(); auto it2 = inputs.at(1)->cbegin(); // weighting is scalar if (weightings_.shape().size() == static_cast<SizeType>(1)) { while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * weightings_(0); ++it1; ++it2; } } // weighting tensor is same shape as input (one weight for every parameter) else if (weightings_.shape() == inputs.at(0)->shape()) { auto w_it = weightings_.cbegin(); while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * (*w_it); ++it1; ++it2; ++w_it; } } // weighting is a batch_size vector (one weight per data point) else if (weightings_.shape() == std::vector<SizeType>{data_size}) { SizeType data_count = 0; SizeType data_stride; fetch::math::Divide(inputs.at(0)->size(), weightings_.size(), data_stride); auto w_it = weightings_.cbegin(); while (it1.is_valid()) { DataType d = (*it1) - (*it2); output(0, 0) += (d * d) * (*w_it); ++it1; ++it2; ++data_count; if (data_count == data_stride) { data_count = 0; ++w_it; } } } // divide by number of elements fetch::math::Divide(output(0, 0), static_cast<DataType>(inputs.at(0)->size()), output(0, 0)); } // division by 2 allows us to cancel out with a 2 in the derivative for optimisation fetch::math::Divide(output(0, 0), static_cast<DataType>(2), output(0, 0)); } /** * Gradients for Mean Square Error Loss would usually be of the form: * grad[0] = 2 * err * (in[0] - in[1]) / data_size * grad[1] = -2 * err * (in[0] - in[1]) / data_size * * However we make a few alterations: * 1. we ignore the gradient for the ground truth (i.e. grad[1]), * 2. we drop the 2 since we divide by 2 in forward pass, * 3. we must incorporate the weightings, * * so the modified gradient is computed as: * grad[0] = (err * (in[0] - in[1]) * weighting) / data_size * grad[1] = grad[0] -- SHOULD NOT BE USED * * @param inputs vector of input_tensor and ground_truth tensor (order is important) * @param error_signal error_signal passed back from next layer - since there should not be a next * layer the calling function is required to set this to a tensor of size 1 and value 1 * @return */ std::vector<ArrayType> Backward(VecTensorType const &inputs, ArrayType const & error_signal) override { FETCH_UNUSED(error_signal); assert(inputs.size() == 2); assert(inputs.at(0)->shape() == inputs.at(1)->shape()); ArrayType return_signal(inputs.front()->shape()); SizeType data_size = inputs.at(0)->shape(inputs.at(0)->shape().size() - 1); auto count = static_cast<DataType>(data_size); // backprop update rule varies depending on shape of weightings auto a_it = inputs.at(0)->cbegin(); auto b_it = inputs.at(1)->cbegin(); auto r_it = return_signal.begin(); // no weighting if (weightings_.size() == static_cast<SizeType>(0)) { while (r_it.is_valid()) { *r_it = ((*a_it) - (*b_it)) / count; ++a_it; ++b_it; ++r_it; } } else { // weighting is scalar if (weightings_.shape().size() == static_cast<SizeType>(1)) { auto weight_over_count = weightings_(0) / count; while (r_it.is_valid()) { *r_it = ((*a_it) - (*b_it)) * weight_over_count; ++a_it; ++b_it; ++r_it; } } // weighting tensor is same shape as input (one weight for every parameter) else if (weightings_.shape() == inputs.at(0)->shape()) { auto w_it = weightings_.cbegin(); while (r_it.is_valid()) { *r_it = (((*a_it) - (*b_it)) * (*w_it)) / (count); ++a_it; ++b_it; ++r_it; ++w_it; } } // weighting is a batch_size vector (one weight per data point) else if (weightings_.shape() == std::vector<SizeType>{data_size}) { auto w_it = weightings_.cbegin(); SizeType data_count = 0; SizeType data_stride; fetch::math::Divide(inputs.at(0)->size(), weightings_.size(), data_stride); while (r_it.is_valid()) { *r_it = (((*a_it) - (*b_it)) * (*w_it)) / (count); ++a_it; ++b_it; ++r_it; // update weight value once per data point ++data_count; if (data_count == data_stride) { data_count = 0; ++w_it; } } } else { throw std::runtime_error("input or weightings_shape invalid"); } } return {return_signal, return_signal}; } std::vector<typename T::SizeType> ComputeOutputShape(VecTensorType const &inputs) const override { FETCH_UNUSED(inputs); return {1, 1}; } static constexpr char const *DESCRIPTOR = "MeanSquareErrorLoss"; private: ArrayType weightings_; }; } // namespace ops } // namespace ml } // namespace fetch
29.971074
100
0.560182
jinmannwong
42f6531ebc2e944c59b698966f111aeaab0a16ae
505
hpp
C++
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/data/collection.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/lang/object.hpp> #include <xul/data/iterator.hpp> #include <xul/data/element_traits.hpp> namespace xul { template <typename T, typename TraitsT = element_traits<T> > class collection : public object { public: typedef T element_type; typedef TraitsT traits_type; virtual int get_count() const = 0; virtual iterator<typename TraitsT::const_accessor_type>* iterate() const = 0; virtual iterator<typename TraitsT::accessor_type>* iterate_ref() = 0; }; }
20.2
81
0.728713
hindsights
42f93e5e12f8e7523524e1bf42cac2b1bbcc6b15
1,211
cc
C++
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
6
2015-03-03T14:22:29.000Z
2021-07-20T13:20:28.000Z
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
null
null
null
unit-test/test_thread_group.cc
anqin/trident
1291596db0532b07865920b46165722a6c6244f4
[ "BSD-3-Clause" ]
5
2015-03-03T14:30:18.000Z
2018-04-12T06:01:39.000Z
// Copyright (c) 2014 The Trident 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 <gtest/gtest.h> #include <trident/thread_group.h> #include <trident/closure.h> class ThreadGroupTest: public ::testing::Test { protected: ThreadGroupTest() {} virtual ~ThreadGroupTest() {} virtual void SetUp() { // Called before every TEST_F(ThreadGroupTest, *) } virtual void TearDown() { // Called after every TEST_F(ThreadGroupTest, *) } }; static void test_1_function(bool* called) { *called = true; } TEST_F(ThreadGroupTest, test_1) { trident::ThreadGroup* thread_group = new trident::ThreadGroup(4); bool dispatch_called = false; thread_group->dispatch(trident::NewClosure(&test_1_function, &dispatch_called)); bool post_called = false; thread_group->post(trident::NewClosure(&test_1_function, &post_called)); delete thread_group; ASSERT_TRUE(dispatch_called); ASSERT_TRUE(post_called); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } /* vim: set ts=4 sw=4 sts=4 tw=100 */
23.288462
84
0.690339
anqin
42fd14d29eb945747cf63df671ab8fe8a34d816d
51,984
cpp
C++
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
91
2017-11-28T07:23:09.000Z
2022-03-28T08:31:51.000Z
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
59
2017-11-28T06:12:18.000Z
2022-03-18T09:00:59.000Z
src/TSSequencerWidgetBase.cpp
j4s0n-c/trowaSoft-VCV
9cd0d05607c88e95200472725df1d032b42130cd
[ "MIT" ]
15
2017-11-28T13:42:35.000Z
2021-12-26T08:03:37.000Z
#include <string.h> #include <stdio.h> //#include "widgets.hpp" #include "trowaSoft.hpp" using namespace rack; //#include "dsp/digital.hpp" #include "trowaSoftComponents.hpp" #include "trowaSoftUtilities.hpp" #include "TSSequencerModuleBase.hpp" #include "TSSequencerWidgetBase.hpp" #include "TSOSCConfigWidget.hpp" //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSequencerWidgetBase() - Base constructor. // Instantiate a trowaSoft Sequencer widget. v0.60 must have module as param. // @seqModule : (IN) Pointer to the sequencer module. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TSSequencerWidgetBase::TSSequencerWidgetBase(TSSequencerModuleBase* seqModule) : TSSModuleWidgetBase(seqModule, /*randomizeParameters*/ false) { box.size = Vec(26 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT); return; } //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Add common controls to the UI widget for trowaSoft sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::addBaseControls(bool addGridLines) { TSSequencerModuleBase *thisModule = NULL; if (this->module != NULL) { thisModule = dynamic_cast<TSSequencerModuleBase*>(this->module); } bool isPreview = thisModule == NULL; //////////////////////////////////// // DISPLAY //////////////////////////////////// { display = new TSSeqDisplay(); display->box.pos = Vec(13, 24); display->box.size = Vec(363, 48); display->module = thisModule; addChild(display); } //////////////////////////////////// // OSC configuration screen. // Should be a popup but J just wants it on the screen. //////////////////////////////////// if (!isPreview) { TSOSCConfigWidget* oscConfig = new TSOSCConfigWidget(thisModule, TSSequencerModuleBase::ParamIds::OSC_SAVE_CONF_PARAM, TSSequencerModuleBase::ParamIds::OSC_AUTO_RECONNECT_PARAM, thisModule->oscCurrentClient, thisModule->currentOSCSettings.oscTxIpAddress.c_str(), thisModule->currentOSCSettings.oscTxPort, thisModule->currentOSCSettings.oscRxPort); oscConfig->setVisible(false); oscConfig->box.pos = display->box.pos; oscConfig->box.size = display->box.size; this->oscConfigurationScreen = oscConfig; addChild(oscConfig); } //////////////////////////////////// // Pattern Sequencer Configuration / Auto-Play Patterns //////////////////////////////////// if (!isPreview && thisModule->allowPatternSequencing) { pattSeqConfigurationScreen = new TSSeqPatternSeqConfigWidget(thisModule); pattSeqConfigurationScreen->setVisible(false); pattSeqConfigurationScreen->box.pos = display->box.pos; pattSeqConfigurationScreen->box.size = display->box.size; addChild(pattSeqConfigurationScreen); } //////////////////////////////////// // Labels //////////////////////////////////// { FramebufferWidget* labelContainer = new FramebufferWidget(); labelContainer->box.pos = Vec(0, 0); labelContainer->box.size = Vec(box.size.x, 380); addChild(labelContainer); labelArea = new TSSeqLabelArea(); labelArea->box.pos = Vec(0, 0); labelArea->box.size = Vec(box.size.x, 380); labelArea->module = thisModule; labelArea->drawGridLines = addGridLines; labelContainer->addChild(labelArea); //addChild(labelArea); } // Screws: addChild(createWidget<ScrewBlack>(Vec(0, 0))); addChild(createWidget<ScrewBlack>(Vec(box.size.x - 15, 0))); addChild(createWidget<ScrewBlack>(Vec(0, box.size.y - 15))); addChild(createWidget<ScrewBlack>(Vec(box.size.x - 15, box.size.y - 15))); // Input Controls ================================================== // Run (Toggle) NVGcolor lightColor = nvgRGBAf(0.7, 0.7, 0.7, 0.8); //TSColors::COLOR_WHITE Vec btnSize = Vec(50,22); addParam(createParam<TS_PadBtn>(Vec(15, 320), thisModule, TSSequencerModuleBase::ParamIds::RUN_PARAM));//, 0.0, 1.0, 0.0)); TS_LightString* item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 320), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::RUNNING_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "RUN"; addChild(item); // Reset (Momentary) addParam(createParam<TS_PadBtn>(Vec(15, 292), thisModule, TSSequencerModuleBase::ParamIds::RESET_PARAM));//, 0.0, 1.0, 0.0)); item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 292), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::RESET_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "RESET"; addChild(item); // Paste button: addParam(createParam<TS_PadBtn>(Vec(15, 115), thisModule, TSSequencerModuleBase::ParamIds::PASTE_PARAM));//, 0.0, 1.0, 0.0)); item = dynamic_cast<TS_LightString*>(TS_createColorValueLight<TS_LightString>(/*pos */ Vec(15, 115), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::PASTE_LIGHT, /* size */ btnSize, /* color */ lightColor)); item->lightString = "PASTE"; // if (!isPreview) // thisModule->pasteLight = item; pasteLight = item; addChild(item); // Top Knobs : Keep references for later int knobRow = 79; int knobStart = 27; int knobSpacing = 61; TS_RoundBlackKnob* outKnobPtr = NULL; // Pattern Playback Select (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart, knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_PATTERN_PLAY_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_PATTERNS - 1, /*default value*/ 0.0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Clock BPM (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 1), knobRow), thisModule, TSSequencerModuleBase::ParamIds::BPM_PARAM));//, TROWA_SEQ_BPM_KNOB_MIN, TROWA_SEQ_BPM_KNOB_MAX, (TROWA_SEQ_BPM_KNOB_MAX + TROWA_SEQ_BPM_KNOB_MIN) / 2)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; addParam(outKnobPtr); // Steps (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 2), knobRow), thisModule, TSSequencerModuleBase::ParamIds::STEPS_PARAM));//, 1.0, this->maxSteps, this->maxSteps)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Output Mode (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 3), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_OUTPUT_VALUE_MODE_PARAM));//, 0, TROWA_SEQ_NUM_MODES - 1, TSSequencerModuleBase::ValueMode::VALUE_TRIGGER)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->minAngle = -0.6*M_PI; outKnobPtr->maxAngle = 0.6*M_PI; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Pattern Edit Select (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 4), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_PATTERN_EDIT_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_PATTERNS - 1, /*default value*/ 0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); // Selected Gate/Voice/Channel (Knob) outKnobPtr = dynamic_cast<TS_RoundBlackKnob*>(createParam<TS_RoundBlackKnob>(Vec(knobStart + (knobSpacing * 5), knobRow), thisModule, TSSequencerModuleBase::ParamIds::SELECTED_CHANNEL_PARAM));//, /*min*/ 0.0, /*max*/ TROWA_SEQ_NUM_CHNLS - 1, /*default value*/ 0)); if (!isPreview) outKnobPtr->getParamQuantity()->randomizeEnabled = false; // outKnobPtr->allowRandomize = false; outKnobPtr->snap = true; // [Rack v2]: Knob::snap doesn't seem to work anymore. Use ParamQuantity::snapEnabled. addParam(outKnobPtr); //======================================================= // Small buttons next to knobs //======================================================= Vec ledSize = Vec(15,15); int dx = 28; float xLightOffset = 1.5f; float yLightOffset = 1.5f; TS_LEDButton* btn; knobStart += 2; int y = knobRow; int x = knobStart; Vec ledBtnSize = Vec(ledSize.x - 2, ledSize.y - 2); //-------------------------------------------------------------------------- // PATTERN SEQ: Pattern Sequencing Configuration (+Config/Enabled Lights): //-------------------------------------------------------------------------- x = knobStart + dx; // 30 if (!isPreview && thisModule->allowPatternSequencing) { btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(x, y), module, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_SHOW_CONFIG_PARAM)); btn->setSize(ledBtnSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset, y + yLightOffset), module, TSSequencerModuleBase::LightIds::PATTERN_SEQ_CONFIGURE_LIGHT, ledSize, TSColors::COLOR_WHITE)); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset + 2, y + yLightOffset + 2), module, TSSequencerModuleBase::LightIds::PATTERN_SEQ_ENABLED_LIGHT, Vec(ledSize.x - 4, ledSize.y - 4), TS_PATTERN_SEQ_STATUS_COLOR)); } //------------------------------------------------------- // OSC: Configuration Button (+Config/Enabled Lights): //------------------------------------------------------- x = knobStart + (knobSpacing * 3) + dx; // 30 if (isPreview || thisModule->allowOSC) { btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(x, y), module, TSSequencerModuleBase::ParamIds::OSC_SHOW_CONF_PARAM));//, 0, 1, 0)); btn->setSize(ledBtnSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset, y + yLightOffset), module, TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT, ledSize, TSColors::COLOR_WHITE)); addChild(TS_createColorValueLight<ColorValueLight>(Vec(x + xLightOffset + 2, y + yLightOffset + 2), module, TSSequencerModuleBase::LightIds::OSC_ENABLED_LIGHT, Vec(ledSize.x - 4, ledSize.y - 4), TSOSC_STATUS_COLOR)); } ColorValueLight* lightPtr = NULL; //------------------------------------------------------- // COPY: Pattern Copy button: //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 4) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::COPY_PATTERN_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); lightPtr = dynamic_cast<ColorValueLight*>(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 4) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::COPY_PATTERN_LIGHT, ledSize, TSColors::COLOR_WHITE)); copyPatternLight = lightPtr; addChild(lightPtr); //------------------------------------------------------- // COPY: Channel Copy button: //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 5) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::COPY_CHANNEL_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); lightPtr = dynamic_cast<ColorValueLight*>(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 5) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::COPY_CHANNEL_LIGHT, ledSize, TSColors::COLOR_WHITE)); copyChannelLight = lightPtr; addChild(lightPtr); //------------------------------------------------------- // CHANGE BPM CALC NOTE (1/4, 1/8, 1/8T, 1/16) //------------------------------------------------------- btn = dynamic_cast<TS_LEDButton*>(createParam<TS_LEDButton>(Vec(knobStart + (knobSpacing * 1) + dx, knobRow), module, TSSequencerModuleBase::ParamIds::SELECTED_BPM_MULT_IX_PARAM));//, 0, 1, 0)); btn->setSize(ledSize); addParam(btn); addChild(TS_createColorValueLight<ColorValueLight>(Vec(knobStart + (knobSpacing * 1) + dx + xLightOffset, knobRow + yLightOffset), module, TSSequencerModuleBase::LightIds::SELECTED_BPM_MULT_IX_LIGHT, ledSize, TSColors::COLOR_WHITE)); // Input Jacks: int xStart = 10; int ySpacing = 28; int portStart = 143; // Selected Pattern Playback: addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 0)), thisModule, TSSequencerModuleBase::InputIds::SELECTED_PATTERN_PLAY_INPUT)); // Clock addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 1)), thisModule, TSSequencerModuleBase::InputIds::BPM_INPUT)); // Steps addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 2)), thisModule, TSSequencerModuleBase::InputIds::STEPS_INPUT)); // External Clock addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 3)), thisModule, TSSequencerModuleBase::InputIds::EXT_CLOCK_INPUT)); // Reset addInput(TS_createInput<TS_Port>(Vec(xStart, portStart + (ySpacing * 4)), thisModule, TSSequencerModuleBase::InputIds::RESET_INPUT)); // Outputs ================================================== // Loop through each channel/voice/gate y = 115; x = 314; int v = 0; float jackDiameter = 20.5; // 28.351 float add = 0; Vec outputLightSize = Vec(jackDiameter + add, jackDiameter + add); const NVGcolor* channelColors = NULL; if (!isPreview) { channelColors = thisModule->voiceColors; } else { channelColors = TSColors::CHANNEL_COLORS; // Point to our default array } for (int r = 0; r < 8; r++) { for (int c = 0; c < 2; c++) { // Triggers / Gates / Output: addOutput(TS_createOutput<TS_Port>(Vec(x, y), thisModule, TSSequencerModuleBase::OutputIds::CHANNELS_OUTPUT+v, /*color*/ channelColors[v])); // Match the color to the trigger/gate/output: addChild(TS_createColorValueLight<TS_LightRing>(/*position*/ Vec(x + 5, y + 5), /*thisModule*/ thisModule, /*lightId*/ TSSequencerModuleBase::LightIds::CHANNEL_LIGHTS+v, /*size*/ outputLightSize, /*lightColor*/ channelColors[v % 16], /*backColor*/ channelColors[v % 16])); if (!isPreview) thisModule->lights[TSSequencerModuleBase::LightIds::CHANNEL_LIGHTS + v].value = 0; x += 36; v++; } // end for y += 28; // Next row x = 314; } // end loop through NxM grid return; } // end addBaseControls() //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // step(void) //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::step() { if (this->module == NULL) return; TSSequencerModuleBase* thisModule = dynamic_cast<TSSequencerModuleBase*>(module); //------------------------------------ // Step Matrix Color //------------------------------------ if (padLightPtrs && colorRGBNotEqual(lastStepMatrixColor, thisModule->currentStepMatrixColor)) { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { padLightPtrs[r][c]->setColor(thisModule->currentStepMatrixColor); } } } lastStepMatrixColor = thisModule->currentStepMatrixColor; //------------------------------------ // Copy & Paste //------------------------------------ // Change colors of our lights here if (colorRGBNotEqual(thisModule->currentCopyChannelColor, copyChannelLight->color)) { copyChannelLight->setColor(thisModule->currentCopyChannelColor); } if (colorRGBNotEqual(thisModule->currentPasteColor, pasteLight->color)) { pasteLight->setColor(thisModule->currentPasteColor); } //------------------------------------ // Pattern Sequencing //------------------------------------ if (thisModule->allowPatternSequencing) { if (pattSeqConfigurationScreen != NULL) { thisModule->lastShowPatternSequencingConfig = thisModule->showPatternSequencingConfig; if (thisModule->patternSeqConfigTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::PATTERN_SEQ_SHOW_CONFIG_PARAM].getValue())) { thisModule->showPatternSequencingConfig = !thisModule->showPatternSequencingConfig; // Set the Configuration Visible if (thisModule->showPatternSequencingConfig) { // SHOW Pattern Config this->display->showDisplay = false; pattSeqConfigurationScreen->setVisible(true); pattSeqConfigurationScreen->ckEnabled->checked = thisModule->patternSequencingOn; // Hide OSC Config thisModule->oscShowConfigurationScreen = false; this->oscConfigurationScreen->setVisible(false); thisModule->lights[TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT].value = 0.0f; } else { // Hide Pattern Config this->display->showDisplay = !thisModule->oscShowConfigurationScreen; pattSeqConfigurationScreen->setVisible(false); } } // end if show config button pressed. } } // end if we are doing pattern sequencing //------------------------------------ // OSC //------------------------------------ if (thisModule->oscConfigTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::OSC_SHOW_CONF_PARAM].getValue())) { thisModule->oscShowConfigurationScreen = !thisModule->oscShowConfigurationScreen; thisModule->lights[TSSequencerModuleBase::LightIds::OSC_CONFIGURE_LIGHT].value = (thisModule->oscShowConfigurationScreen) ? 1.0 : 0.0; this->oscConfigurationScreen->setVisible(thisModule->oscShowConfigurationScreen); this->display->showDisplay = !thisModule->oscShowConfigurationScreen; if (thisModule->oscShowConfigurationScreen) { thisModule->showPatternSequencingConfig = false; // Stop showing pattern configuration if showing if (pattSeqConfigurationScreen != NULL) pattSeqConfigurationScreen->setVisible(false); if (!thisModule->oscInitialized) { // Make sure the ports are available int p = TSOSCConnector::PortInUse(thisModule->currentOSCSettings.oscTxPort); if (p > 0 && p != thisModule->oscId) thisModule->currentOSCSettings.oscTxPort = TSOSCConnector::GetAvailablePortTrans(thisModule->oscId, thisModule->currentOSCSettings.oscTxPort); p = TSOSCConnector::PortInUse(thisModule->currentOSCSettings.oscRxPort); if (p > 0 && p != thisModule->oscId) thisModule->currentOSCSettings.oscRxPort = TSOSCConnector::GetAvailablePortRecv(thisModule->oscId, thisModule->currentOSCSettings.oscRxPort); } this->oscConfigurationScreen->setValues(thisModule->currentOSCSettings.oscTxIpAddress, thisModule->currentOSCSettings.oscTxPort, thisModule->currentOSCSettings.oscRxPort); this->oscConfigurationScreen->ckAutoReconnect->checked = thisModule->oscReconnectAtLoad; this->oscConfigurationScreen->setSelectedClient(thisModule->oscCurrentClient); // OSC Client this->oscConfigurationScreen->btnActionEnable = !thisModule->oscInitialized; this->oscConfigurationScreen->errorMsg = ""; if (thisModule->oscError) { this->oscConfigurationScreen->errorMsg = "Error connecting to " + thisModule->currentOSCSettings.oscTxIpAddress; } this->oscConfigurationScreen->setVisible(true); } else { this->oscConfigurationScreen->setVisible(false); } } if (thisModule->oscShowConfigurationScreen) { // Check for enable/disable if (thisModule->oscConnectTrigger.process(thisModule->params[TSSequencerModuleBase::ParamIds::OSC_SAVE_CONF_PARAM].getValue())) { if (oscConfigurationScreen->btnActionEnable) { // Enable OSC ------------------------------------------------------------------------ // User checked to connect if (!this->oscConfigurationScreen->isValidIpAddress()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("IP Address is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid IP Address."; this->oscConfigurationScreen->tbIpAddress->requestFocus(); } else if (!this->oscConfigurationScreen->isValidTxPort()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Tx Port is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid Output Port (0-" + std::to_string(0xFFFF) + ")."; this->oscConfigurationScreen->tbTxPort->requestFocus(); } else if (!this->oscConfigurationScreen->isValidRxPort()) { #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Rx Port is not valid."); #endif this->oscConfigurationScreen->errorMsg = "Invalid Input Port (0-" + std::to_string(0xFFFF) + ")."; this->oscConfigurationScreen->tbRxPort->requestFocus(); } else { // Try to connect #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Save OSC Configuration clicked, save information for module."); #endif this->oscConfigurationScreen->errorMsg = ""; thisModule->oscNewSettings.oscTxIpAddress = this->oscConfigurationScreen->tbIpAddress->text.c_str(); thisModule->oscNewSettings.oscTxPort = this->oscConfigurationScreen->getTxPort(); thisModule->oscNewSettings.oscRxPort = this->oscConfigurationScreen->getRxPort(); thisModule->oscCurrentClient = this->oscConfigurationScreen->getSelectedClient(); thisModule->oscCurrentAction = TSSequencerModuleBase::OSCAction::Enable; thisModule->oscReconnectAtLoad = this->oscConfigurationScreen->ckAutoReconnect->checked; #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Set osc current action to %d.", thisModule->oscCurrentAction); #endif } } // end if enable osc else { // Disable OSC ------------------------------------------------------------------ #if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED DEBUG("Disable OSC clicked."); #endif this->oscConfigurationScreen->errorMsg = ""; thisModule->oscCurrentAction = TSSequencerModuleBase::OSCAction::Disable; } // end else disable OSC } // end if OSC Save btn pressed else { if (thisModule->oscError) { if (this->oscConfigurationScreen->errorMsg.empty()) this->oscConfigurationScreen->errorMsg = "Error connecting to " + thisModule->currentOSCSettings.oscTxIpAddress + "."; } } // Current status of OSC if (thisModule->useOSC && thisModule->oscInitialized) { // Now we have a checkbox up top where statusMsg used to be, so let's not use it for now. //this->oscConfigurationScreen->statusMsg = OSCClientAbbr[thisModule->oscCurrentClient] + " " + thisModule->currentOSCSettings.oscTxIpAddress; //this->oscConfigurationScreen->statusMsg2 = ":" + std::to_string(thisModule->currentOSCSettings.oscTxPort) // + " :" + std::to_string(thisModule->currentOSCSettings.oscRxPort); this->oscConfigurationScreen->statusMsg2 = OSCClientAbbr[thisModule->oscCurrentClient] + " " + thisModule->currentOSCSettings.oscTxIpAddress; this->oscConfigurationScreen->btnActionEnable = false; } else { this->oscConfigurationScreen->successMsg = ""; this->oscConfigurationScreen->statusMsg = "";// "OSC Not Connected"; this->oscConfigurationScreen->statusMsg2 = "OSC Not Connected"; //""; this->oscConfigurationScreen->btnActionEnable = true; } } // end if show OSC config screen ModuleWidget::step(); return; } // end step() struct seqRandomSubMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; enum ShiftType { // Current Edit Pattern & Channel CurrentChannelOnly, // Current Edit Pattern, All Channels ThisPattern, // All patterns, all channels AllPatterns, // Song mode / Pattern sequence. SongMode }; ShiftType Target = ShiftType::CurrentChannelOnly; seqRandomSubMenuItem(std::string text, ShiftType target, bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->Target = target; this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; } ~seqRandomSubMenuItem() { sequencerModule = NULL; } void onAction(const event::Action &e) override { switch (this->Target) { case ShiftType::CurrentChannelOnly: sequencerModule->randomize(sequencerModule->currentPatternEditingIx, sequencerModule->currentChannelEditingIx, useStucturedRandom); break; case ShiftType::ThisPattern: sequencerModule->randomize(sequencerModule->currentPatternEditingIx, TROWA_SEQ_COPY_CHANNELIX_ALL, useStucturedRandom); break; case ShiftType::SongMode: // PATTERN SEQUENCE sequencerModule->randomizePatternSequence(useStucturedRandom); break; default: // All steps sequencerModule->randomize(TROWA_INDEX_UNDEFINED, TROWA_SEQ_COPY_CHANNELIX_ALL, useStucturedRandom); break; } } }; struct seqRandomSubMenu : Menu { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; seqRandomSubMenu(bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size = Vec(200, 60); this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; return; } ~seqRandomSubMenu() { sequencerModule = NULL; } void createChildren() { addChild(new seqRandomSubMenuItem("Current Edit Channel", seqRandomSubMenuItem::ShiftType::CurrentChannelOnly, this->useStucturedRandom, this->sequencerModule)); addChild(new seqRandomSubMenuItem("Current Edit Pattern", seqRandomSubMenuItem::ShiftType::ThisPattern, this->useStucturedRandom, this->sequencerModule)); addChild(new seqRandomSubMenuItem("ALL Patterns", seqRandomSubMenuItem::ShiftType::AllPatterns, this->useStucturedRandom, this->sequencerModule)); if (sequencerModule->allowPatternSequencing) addChild(new seqRandomSubMenuItem("Song Mode", seqRandomSubMenuItem::ShiftType::SongMode, this->useStucturedRandom, this->sequencerModule)); return; } }; // First tier menu item. Create Submenu struct seqRandomMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; bool useStucturedRandom; seqRandomMenuItem(std::string text, bool useStructured, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->useStucturedRandom = useStructured; this->sequencerModule = seqModule; return; } ~seqRandomMenuItem() { sequencerModule = NULL; return; } Menu *createChildMenu() override { seqRandomSubMenu* menu = new seqRandomSubMenu(useStucturedRandom, sequencerModule); menu->sequencerModule = this->sequencerModule; menu->createChildren(); menu->box.size = Vec(200, 60); return menu; } }; // Initialize menu items. struct seqInitializeMenuItem : MenuItem { TSSequencerModuleBase* sequencerModule; enum InitType { // Current Edit Pattern & Channel CurrentChannelOnly, // Current Edit Pattern, All Channels ThisPattern, // All patterns, all channels AllPatterns, // Song mode / Pattern sequence. SongMode }; InitType Target = InitType::CurrentChannelOnly; seqInitializeMenuItem(std::string text, InitType target, TSSequencerModuleBase* seqModule) { this->box.size.x = 200; this->text = text; this->Target = target; this->sequencerModule = seqModule; } ~seqInitializeMenuItem() { sequencerModule = NULL; } void onAction(const event::Action &e) override { switch (this->Target) { case InitType::ThisPattern: sequencerModule->reset(sequencerModule->currentPatternEditingIx, TROWA_INDEX_UNDEFINED); break; case InitType::CurrentChannelOnly: sequencerModule->reset(sequencerModule->currentPatternEditingIx, sequencerModule->currentChannelEditingIx); break; case InitType::SongMode: // PATTERN SEQUENCE sequencerModule->resetPatternSequence(); break; default: // All steps sequencerModule->reset(TROWA_INDEX_UNDEFINED, TROWA_INDEX_UNDEFINED); break; } return; } }; //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // createContextMenu() // Create context menu with more random options for sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSequencerWidgetBase::appendContextMenu(ui::Menu *menu) { MenuLabel *spacerLabel = new MenuLabel(); menu->addChild(spacerLabel); TSSequencerModuleBase* sequencerModule = dynamic_cast<TSSequencerModuleBase*>(module); MenuLabel* modeLabel = NULL; //-------- Initialize ----// modeLabel = new MenuLabel(); modeLabel->text = "Initialize Options"; menu->addChild(modeLabel); menu->addChild(new seqInitializeMenuItem("Current Edit Channel", seqInitializeMenuItem::InitType::CurrentChannelOnly, sequencerModule)); menu->addChild(new seqInitializeMenuItem("Current Edit Pattern", seqInitializeMenuItem::InitType::ThisPattern, sequencerModule)); menu->addChild(new seqInitializeMenuItem("ALL Patterns", seqInitializeMenuItem::InitType::AllPatterns, sequencerModule)); if (sequencerModule->allowPatternSequencing) { menu->addChild(new seqInitializeMenuItem("Song Mode", seqInitializeMenuItem::InitType::SongMode, sequencerModule)); } //-------- Spacer -------- // modeLabel = new MenuLabel(); modeLabel->text = ""; menu->addChild(modeLabel); //-------- Random ------- // modeLabel = new MenuLabel(); modeLabel->text = "Random Options"; menu->addChild(modeLabel); //menu->pushChild(modeLabel); menu->addChild(new seqRandomMenuItem("> All Steps Random", false, sequencerModule)); menu->addChild(new seqRandomMenuItem("> Structured Random", true, sequencerModule)); return; } //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqLabelArea // Draw labels on our sequencer. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // draw() // @args.vg : (IN) NVGcontext to draw on // Draw labels on a trowaSoft sequencer. // (Common across trigSeq, voltSeq, multiSeq). //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqLabelArea::draw(const DrawArgs &args) { // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 1); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); nvgFillColor(args.vg, textColor); nvgFontSize(args.vg, fontSize); /// MAKE LABELS HERE int x = 45; int y = 163; int dy = 28; // Selected Pattern Playback: nvgText(args.vg, x, y, "PAT", NULL); // Clock y += dy; nvgText(args.vg, x, y, "BPM ", NULL); // Steps y += dy; nvgText(args.vg, x, y, "LNG", NULL); // Ext Clock y += dy; nvgText(args.vg, x, y, "CLK", NULL); // Reset y += dy; nvgText(args.vg, x, y, "RST", NULL); // Outputs nvgFontSize(args.vg, fontSize * 0.95); x = 320; y = 350; nvgText(args.vg, x, y, "OUTPUTS", NULL); // TINY btn labels nvgFontSize(args.vg, fontSize * 0.6); // OSC Labels y = 103; if (module == NULL || module->allowOSC) { x = 242; //240 nvgText(args.vg, x, y, "OSC", NULL); } // Copy button labels: x = 304; // 302 nvgText(args.vg, x, y, "CPY", NULL); x = 364; // 364 nvgText(args.vg, x, y, "CPY", NULL); // BPM divisor/note label: x = 120; //118 nvgText(args.vg, x, y, "DIV", NULL); // Pattern sequence label if (allowPatternSequencing) { x = 60; nvgText(args.vg, x, y, "SEQ", NULL); } if (drawGridLines) { NVGcolor gridColor = nvgRGB(0x44, 0x44, 0x44); nvgBeginPath(args.vg); x = 80; y = 228; nvgMoveTo(args.vg, /*start x*/ x, /*start y*/ y);// Starts new sub-path with specified point as first point x += 225; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, gridColor); nvgStroke(args.vg); // Vertical nvgBeginPath(args.vg); x = 192; y = 116; nvgMoveTo(args.vg, /*start x*/ x, /*start y*/ y);// Starts new sub-path with specified point as first point y += 225; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, gridColor); nvgStroke(args.vg); } return; } // end draw() //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqPatternSeqConfigWidget // Pattern sequencing configuration. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqPatternSeqConfigWidget(); //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- TSSeqPatternSeqConfigWidget::TSSeqPatternSeqConfigWidget(TSSequencerModuleBase* module) { this->box.size = Vec(400, 50); seqModule = module; font = APP->window->loadFont(asset::plugin(pluginInstance, TROWA_DIGITAL_FONT)); labelFont = APP->window->loadFont(asset::plugin(pluginInstance, TROWA_LABEL_FONT)); fontSize = 12; memset(messageStr, '\0', TROWA_DISP_MSG_SIZE); ckEnabled = new TS_ScreenCheckBox(Vec(50, 14), seqModule, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_ON_PARAM, "Enable"); ckEnabled->momentary = false; ckEnabled->box.pos = Vec(250, 20); ckEnabled->checkBoxWidth = 10; ckEnabled->checkBoxHeight = 10; ckEnabled->fontSize = 9; ckEnabled->borderWidth = 0; ckEnabled->padding = 1; ckEnabled->color = TS_PATTERN_SEQ_STATUS_COLOR; addChild(ckEnabled); TS_KnobColored* knobPtr = dynamic_cast<TS_KnobColored*>(createParam<TS_KnobColored>(Vec(200, 15), seqModule, TSSequencerModuleBase::ParamIds::PATTERN_SEQ_LENGTH_PARAM)); knobPtr->init(TS_KnobColored::SizeType::Small, TS_KnobColored::KnobColor::MedGray); knobPtr->getParamQuantity()->randomizeEnabled = false; //knobPtr->allowRandomize = false; knobPtr->snap = true; addChild(knobPtr); //parentWidget->addParam(knobPtr); return; } //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // draw() // @args.vg : (IN) NVGcontext to draw on //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqPatternSeqConfigWidget::draw(const DrawArgs &args) { if (!visible || seqModule == NULL) return; OpaqueWidget::draw(args); // Show the current pattern value int currentPatternIndex = seqModule->currentPatternDataBeingEditedIx; //0-63 int paramId = seqModule->currentPatternDataBeingEditedParamId; int currentPatternVal = (paramId > -1) ? seqModule->params[paramId].getValue() + 1 : -1; // 1-64 int currentPatternLength = seqModule->numPatternsInSequence; NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; float x = 0; int spacing = 61; ///---------------/// /// * Edit Line * /// ///---------------/// float xl_0 = 36.0f; //41.0f; float xl_1 = xl_0 + spacing * 1.5f + 10.0f; const float yline = 5.0f; NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgBeginPath(args.vg); nvgMoveTo(args.vg, xl_0, yline); nvgLineTo(args.vg, xl_1, yline); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); nvgBeginPath(args.vg); nvgFillColor(args.vg, backgroundColor); x = (xl_0 + xl_1) / 2.0f - 11; nvgRect(args.vg, x, yline - 3, 22, 6); nvgFill(args.vg); nvgFillColor(args.vg, groupColor); nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, (xl_0 + xl_1) / 2.0f, 8, "EDIT", NULL); ///-------------/// /// * DISPLAY * /// ///-------------/// nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); // Current Edit Pattern Index (Sequence #/Step #) nvgFillColor(args.vg, textColor); x = 56;// 26; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "SEQ", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); if (currentPatternIndex > -1) { sprintf(messageStr, "%02d", (currentPatternIndex + 1)); nvgText(args.vg, x + dx, y2, messageStr, NULL); } else { nvgText(args.vg, x + dx, y2, "--", NULL); } // Current PATTERN Value (control being dragged) nvgFillColor(args.vg, textColor); // Maybe highlight this and the pad being edited? x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); if (currentPatternVal > -1) { sprintf(messageStr, "%02d", currentPatternVal); nvgText(args.vg, x + dx, y2, messageStr, NULL); } else { nvgText(args.vg, x + dx, y2, "--", NULL); } // Pattern Length nvgFillColor(args.vg, textColor); // Maybe highlight this and the pad being edited? x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PLEN", NULL); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); sprintf(messageStr, "%02d", currentPatternLength); nvgText(args.vg, x + dx, y2, messageStr, NULL); return; } // Pattern Sequence Config Widget draw() //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // TSSeqDisplay // A top digital display for trowaSoft sequencers. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- //=============================================================================== //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Draw the normal default overview. //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqDisplay::drawNormalView(const DrawArgs &args) { bool isPreview = module == NULL; // May get a NULL module for preview int currPlayPattern = 1; int currEditPattern = 1; int currentChannel = 1; int currentNSteps = 16; float currentBPM = 120; TSSequencerModuleBase::ControlSource currPlayPatternCtrlSrc = TSSequencerModuleBase::ControlSource::UserParameterSrc; NVGcolor currColor = TSColors::COLOR_TS_RED; if (!isPreview) { currColor = module->voiceColors[module->currentChannelEditingIx]; currPlayPattern = module->currentPatternPlayingIx + 1; currEditPattern = module->currentPatternEditingIx + 1; currentChannel = module->currentChannelEditingIx + 1; currentNSteps = module->currentNumberSteps; currentBPM = module->currentBPM; currPlayPatternCtrlSrc = module->patternPlayingControlSource; } // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; int x = 0; int spacing = 61; nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Playing Pattern nvgFillColor(args.vg, textColor); x = 5 + 21; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currPlayPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Little indicator for what is controlling the current playing pattern // // Highest Priority Source (0) - External message (OSC or in future direct MIDI integration) // ExternalMsgSrc = 0, // // Control Voltage Input - Priority (1) // CVInputSrc = 1, // // For like Auto-Pattern-Sequencing - Priority (2) // AutoSrc = 2, // // User Parameter (UI) Control - Priority (3 = Last) // UserParameterSrc = 3 const char *indicator[] = { "EXT", "CV", "SEQ", "USR" }; int x_ind = x + spacing / 2.0f - 12; float smFontSize = fontSize - 5.5; nvgFontSize(args.vg, smFontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); int y_ind = 17; //const float bWidth = 16; //const float bHeight = 8; nvgFillColor(args.vg, textColor); nvgTextAlign(args.vg, NVG_ALIGN_LEFT); //nvgText(args.vg, x_ind, y_ind, indicator[currPlayPatternCtrlSrc], NULL); // Make more room (if you put it at the highest BPM, it will cut it off), so we'll display it vertically const char* lbl = indicator[currPlayPatternCtrlSrc]; int len = static_cast<int>(strlen(lbl)); for (int i = 0; i < len; i++) { const char* end = (i < len-1) ? &(lbl[i + 1]) : NULL; nvgText(args.vg, x_ind, y_ind + i * smFontSize, &(lbl[i]), end); } // for (int s = 0; s < 4; s++) // { // if (s == currPlayPatternCtrlSrc) // { // nvgBeginPath(args.vg); // nvgRect(args.vg, x_ind - bWidth/2.0f, y_ind - bHeight / 2.0f, bWidth, bHeight); // nvgFillColor(args.vg, textColor); // nvgFill(args.vg); // nvgFillColor(args.vg, backgroundColor); // } // else // { // nvgFillColor(args.vg, textColor); // } // nvgText(args.vg, x_ind, y_ind, indicator[s], NULL); // y_ind += 9; // } // end for // Current Playing Speed nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); if (isPreview) sprintf(messageStr, "BPM/%s", BPMOptions[1]->label); else sprintf(messageStr, "BPM/%s", BPMOptions[module->selectedBPMNoteIx]->label); nvgText(args.vg, x, y1, messageStr, NULL); if (!isPreview && module->lastStepWasExternalClock) { sprintf(messageStr, "%s", "CLK"); } else { sprintf(messageStr, "%03.0f", currentBPM); } nvgFontFaceId(args.vg, font->handle); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Playing # Steps nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "LENG", NULL); sprintf(messageStr, "%02d", currentNSteps); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Mode: nvgFillColor(args.vg, nvgRGB(0xda, 0xda, 0xda)); x += spacing + 5; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "MODE", NULL); nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, font->handle); // Mode is now associated to the Channel, so match the channel color: nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color if (!isPreview && module->modeString != NULL) { nvgText(args.vg, x + dx, y2, module->modeString, NULL); } else { nvgText(args.vg, x + dx, y2, "TRIG", NULL); } nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Edit Pattern nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currEditPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Gate/Trigger nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "CHNL", NULL); sprintf(messageStr, "%02d", currentChannel); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // [[[[[[[[[[[[[[[[ EDIT Box Group ]]]]]]]]]]]]]]]]]]]]]]]]]]]]] nvgTextAlign(args.vg, NVG_ALIGN_LEFT); NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgFillColor(args.vg, groupColor); int labelX = 297; x = labelX; // 289 nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, 8, "EDIT", NULL); // Edit Label Line --------------------------------------------------------------- nvgBeginPath(args.vg); // Start top to the left of the text "Edit" int y = 5; nvgMoveTo(args.vg, /*start x*/ x - 3, /*start y*/ y);// Starts new sub-path with specified point as first point.s x = 256;// x - 35;//xOffset + 3 * spacing - 3 + 60; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to Left (Line Start) x = labelX + 22; y = 5; nvgMoveTo(args.vg, /*x*/ x, /*y*/ y); // Right of "Edit" x = box.size.x - 6; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // RHS of box nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); // [[[[[[[[[[[[[[[[ PLAYBACK Box Group ]]]]]]]]]]]]]]]]]]]]]]]]]]]]] groupColor = nvgRGB(0xEE, 0xEE, 0xEE); nvgFillColor(args.vg, groupColor); labelX = 64; x = labelX; nvgFontSize(args.vg, fontSize - 5); // Small font nvgText(args.vg, x, 8, "PLAYBACK", NULL); // Play Back Label Line --------------------------------------------------------------- nvgBeginPath(args.vg); // Start top to the left of the text "Play" y = 5; nvgMoveTo(args.vg, /*start x*/ x - 3, /*start y*/ y);// Starts new sub-path with specified point as first point.s x = 6; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go to the left x = labelX + 52; y = 5; nvgMoveTo(args.vg, /*x*/ x, /*y*/ y); // To the Right of "Playback" x = 165; //x + 62 ; nvgLineTo(args.vg, /*x*/ x, /*y*/ y); // Go Right nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); return; } // end drawNormalView() //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // Draw the edit step view. // @currEditStep : Step number (1 - N). //-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- void TSSeqDisplay::drawEditStepView(const DrawArgs &args, int currEditStep) { bool isPreview = module == NULL; // May get a NULL module for preview int currEditPattern = 1; int currentChannel = 1; float currEditStepVal = 0.0f; int currEditStepParamId = -1; NVGcolor currColor = TSColors::COLOR_TS_RED; if (!isPreview) { currColor = module->voiceColors[module->currentChannelEditingIx]; currEditPattern = module->currentPatternEditingIx + 1; currentChannel = module->currentChannelEditingIx + 1; currEditStepParamId = module->currentStepBeingEditedParamId; currEditStepVal = module->params[currEditStepParamId].getValue(); } // Default Font: nvgFontSize(args.vg, fontSize); nvgFontFaceId(args.vg, font->handle); nvgTextLetterSpacing(args.vg, 2.5); NVGcolor textColor = nvgRGB(0xee, 0xee, 0xee); int y1 = 42; int y2 = 27; int dx = 0; float x = 0; int spacing = 61; nvgTextAlign(args.vg, NVG_ALIGN_CENTER); // Current Edit Pattern nvgFillColor(args.vg, textColor); x = 26; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "PATT", NULL); sprintf(messageStr, "%02d", currEditPattern); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Channel nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "CHNL", NULL); sprintf(messageStr, "%02d", currentChannel); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Step nvgFillColor(args.vg, currColor); // Match the Gate/Trigger color x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, x, y1, "STEP", NULL); sprintf(messageStr, "%02d", currEditStep); nvgFontSize(args.vg, fontSize * 1.5); // Large font nvgFontFaceId(args.vg, font->handle); nvgText(args.vg, x + dx, y2, messageStr, NULL); // Current Edit Step Value nvgFillColor(args.vg, textColor); x += spacing; nvgFontSize(args.vg, fontSize); // Small font nvgFontFaceId(args.vg, labelFont->handle); if (sequencerValueModePtr != NULL) { nvgText(args.vg, x, y1, sequencerValueModePtr->displayName, NULL); } else { nvgText(args.vg, x, y1, "VAL", NULL); } nvgFontSize(args.vg, fontSize * 1.3); // Large font nvgFontFaceId(args.vg, font->handle); if (sequencerValueModePtr != NULL) { sequencerValueModePtr->GetDisplayString(currEditStepVal, messageStr); } else { sprintf(messageStr, "%4.1f", currEditStepVal); } nvgText(args.vg, x + dx, y2, messageStr, NULL); ///---------------/// /// * Edit Line * /// ///---------------/// float xl_0 = 5.0f; float mult = 3.7f; if (module != NULL) { if (module->selectedOutputValueMode == TSSequencerModuleBase::ValueMode::VALUE_VOLT) mult = 4.0f; // Longer values } float xl_1 = xl_0 + spacing * mult; const float yline = 5.0f; NVGcolor groupColor = nvgRGB(0xDD, 0xDD, 0xDD); nvgBeginPath(args.vg); nvgMoveTo(args.vg, xl_0, yline); nvgLineTo(args.vg, xl_1, yline); nvgStrokeWidth(args.vg, 1.0); nvgStrokeColor(args.vg, groupColor); nvgStroke(args.vg); nvgBeginPath(args.vg); nvgFillColor(args.vg, backgroundColor); x = (xl_0 + xl_1) / 2.0f - 11; nvgRect(args.vg, x, yline - 3, 22, 6); nvgFill(args.vg); nvgFillColor(args.vg, groupColor); nvgTextAlign(args.vg, NVG_ALIGN_CENTER); nvgFontSize(args.vg, fontSize - 5); // Small font nvgFontFaceId(args.vg, labelFont->handle); nvgText(args.vg, (xl_0 + xl_1) / 2.0f, 8, "EDIT", NULL); // if (lastStepEditShownParamId != currEditStepParamId || lastStepEditShownValue != currEditStepVal) // { // DEBUG("Param Value Change. Step #%d. Id = %d, Value = %4.1f", currEditStep, currEditStepParamId, currEditStepVal); // } lastStepEditShownParamId = currEditStepParamId; lastStepEditShownValue = currEditStepVal; return; } // end drawEditStepView()
38.336283
289
0.636734
j4s0n-c
6e02834dd17eb1d9d1c81772ff522533a147c9f8
2,368
cpp
C++
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
201-300/269-Alien_Dictionary-h.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// There is a new alien language which uses the latin alphabet. However, the // order among letters are unknown to you. You receive a list of non-empty words // from the dictionary, where words are sorted lexicographically by the rules of // this new language. Derive the order of letters in this language. // Example 1: // Input: // [ // "wrt", // "wrf", // "er", // "ett", // "rftt" // ] // Output: "wertf" // Example 2: // Input: // [ // "z", // "x" // ] // Output: "zx" // Example 3: // Input: // [ // "z", // "x", // "z" // ] // Output: "" // Explanation: The order is invalid, so return "". // Note: // You may assume all letters are in lowercase. // You may assume that if a is a prefix of b, then a must appear before b in the // given dictionary. If the order is invalid, return an empty string. There may // be multiple valid order of letters, return any one of them is fine. class Solution { public: string alienOrder(vector<string> &words) { // after['a'] is the set of chars ordered later than 'a' unordered_map<char, unordered_set<char>> after; // precnt['a'] is the (min) prefix length of 'a' in result // 'xyza', precnt['a'] == 3 unordered_map<char, int> precnt; for (auto &&w : words) for (auto &&c : w) precnt.emplace(c, 0); for (int i = 0; i < words.size() - 1; ++i) { int j = 0, sz = words[i].size(); // safe while (j < sz && words[i][j] == words[i + 1][j]) ++j; if (j == sz) continue; if (after.count(words[i + 1][j]) && after[words[i + 1][j]].count(words[i][j])) return ""; // invalid if (after[words[i][j]].insert(words[i + 1][j]).second) ++precnt[words[i + 1][j]]; } queue<char> q; string ret; for (auto &l : precnt) if (l.second == 0) q.push(l.first); while (!q.empty()) { char c = q.front(); q.pop(); ret += c; if (after.count(c)) for (auto &cc : after[c]) if (--precnt[cc] == 0) q.push(cc); } if (ret.size() != precnt.size()) return ""; return ret; } };
24.163265
80
0.489865
ysmiles
6e07301ca31abe344945c29129c033fc427e00f3
16,175
cpp
C++
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/unittest/UnitTestBatching.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
/* * @file * @author TPOC: [email protected] * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "include/gtest/gtest.h" #include <iostream> #include <vector> #include "../lib/cryptocontext.h" #include "encoding/byteplaintextencoding.h" #include "encoding/intplaintextencoding.h" #include "encoding/packedintplaintextencoding.h" #include "utils/debug.h" using namespace std; using namespace lbcrypto; class UnitTestBatching : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} public: }; /*Simple Encrypt-Decrypt check for DCRTPoly. The assumption is this test case is that everything with respect to lattice and math * layers and cryptoparameters work. This test case is only testing if the resulting plaintext from an encrypt/decrypt returns the same * plaintext * The cyclotomic order is set 2048 *tower size is set to 3*/ TEST(UTLTVBATCHING, Poly_Encrypt_Decrypt) { float stdDev = 4; usint m = 8; BigInteger modulus("2199023288321"); BigInteger rootOfUnity; modulus = NextPrime(modulus, m); rootOfUnity = RootOfUnity(m, modulus); std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); shared_ptr<Poly::Params> ep( new Poly::Params(m, modulus, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(ep, 17, 8, stdDev); cc->Enable(ENCRYPTION); //Regular LWE-NTRU encryption algorithm //////////////////////////////////////////////////////////// //Perform the key generation operation. /////////////////////////////////////////////////////////// LPKeyPair<Poly> kp = cc->KeyGen(); //////////////////////////////////////////////////////////// //Encryption //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertext; ciphertext = cc->Encrypt(kp.publicKey, intArray1, false); //////////////////////////////////////////////////////////// //Decryption //////////////////////////////////////////////////////////// PackedIntPlaintextEncoding intArrayNew; DecryptResult result = cc->Decrypt(kp.secretKey, ciphertext, &intArrayNew, false); if (!result.isValid) { std::cout << "Decryption failed!" << std::endl; exit(1); } EXPECT_EQ(intArrayNew, vectorOfInts1); } TEST(UTLTVBATCHING, Poly_EVALADD) { float stdDev = 4; usint m = 8; BigInteger modulus("2199023288321"); BigInteger rootOfUnity; modulus = NextPrime(modulus, m); rootOfUnity = RootOfUnity(m, modulus); std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsExpected = { 5,5,5,5 }; shared_ptr<Poly::Params> ep( new Poly::Params(m, modulus, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(ep, 17, 8, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); //Regular LWE-NTRU encryption algorithm //////////////////////////////////////////////////////////// //Perform the key generation operation. /////////////////////////////////////////////////////////// LPKeyPair<Poly> kp = cc->KeyGen(); //////////////////////////////////////////////////////////// //Encryption //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); vector<shared_ptr<Ciphertext<Poly>>> ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); //////////////////////////////////////////////////////////// //EvalAdd Operation //////////////////////////////////////////////////////////// vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; ciphertextResult.insert(ciphertextResult.begin(), cc->EvalAdd(ciphertext1.at(0), ciphertext2.at(0)) ); //////////////////////////////////////////////////////////// //Decryption //////////////////////////////////////////////////////////// PackedIntPlaintextEncoding intArrayNew; DecryptResult result = cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); if (!result.isValid) { std::cout << "Decryption failed!" << std::endl; exit(1); } EXPECT_EQ(intArrayNew, vectorOfIntsExpected); } TEST(UTLTVBATCHING, Poly_EVALMULT) { usint ptMod = 17; usint m = 8; usint relin = 1; float stdDev = 4; BigInteger q("2199023288321"); q = NextPrime(q, m); BigInteger rootOfUnity(RootOfUnity(m, q)); shared_ptr<Poly::Params> parms( new Poly::Params(m, q, rootOfUnity) ); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextLTV(parms, ptMod, relin, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); cc->Enable(LEVELEDSHE); //Initialize the public key containers. LPKeyPair<Poly> kp; std::vector<usint> vectorOfInts1 = { 1,2,3,4 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsExpected = { 4,6,6,4 }; kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); vector<shared_ptr<Ciphertext<Poly>>> ciphertextResults; cc->EvalMultKeyGen(kp.secretKey); ciphertextResults.insert(ciphertextResults.begin(), cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0))); PackedIntPlaintextEncoding results; cc->Decrypt(kp.secretKey, ciphertextResults, &results, false); EXPECT_EQ(results, vectorOfIntsExpected); } /*Simple Encrypt-Decrypt check for Poly. The assumption is this test case is that everything with respect to lattice and math * layers and cryptoparameters work. This test case is only testing if the resulting plaintext from an encrypt/decrypt returns the same * plaintext * The cyclotomic order is set to 22 *tower size is set to 3*/ TEST(UTLTVBATCHING, Poly_Encrypt_Decrypt_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("800053"); BigInteger modulusP(p); BigInteger rootOfUnity("59094"); BigInteger bigmodulus("1019642968797569"); BigInteger bigroot("116200103432701"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 8, stdDev); cc->Enable(ENCRYPTION); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext; std::vector<usint> vectorOfInts = { 1,1,1,5,1,4,1,6,1,7 }; PackedIntPlaintextEncoding intArray(vectorOfInts); ciphertext = cc->Encrypt(kp.publicKey, intArray, false); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertext, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfInts); } TEST(UTLTVBATCHING, Poly_EVALADD_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("800053"); BigInteger modulusP(p); BigInteger rootOfUnity("59094"); BigInteger bigmodulus("1019642968797569"); BigInteger bigroot("116200103432701"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 8, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsAdd; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsAdd), std::plus<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); auto ciphertextAdd = cc->EvalAdd(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextAdd); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsAdd); } TEST(UTBVBATCHING, Poly_EVALMULT_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("72385066601"); BigInteger modulusP(p); BigInteger rootOfUnity("69414828251"); BigInteger bigmodulus("77302754575416994210914689"); BigInteger bigroot("76686504597021638023705542"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextBV(params, p, 1, stdDev); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsMult; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsMult), std::multiplies<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); cc->EvalMultKeyGen(kp.secretKey); auto ciphertextMult = cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextMult); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsMult); } TEST(UTFVBATCHING, Poly_EVALMULT_Arb) { PackedIntPlaintextEncoding::Destroy(); usint m = 22; usint p = 89; // we choose s.t. 2m|p-1 to leverage CRTArb BigInteger modulusQ("72385066601"); BigInteger modulusP(p); BigInteger rootOfUnity("69414828251"); BigInteger bigmodulus("77302754575416994210914689"); BigInteger bigroot("76686504597021638023705542"); auto cycloPoly = GetCyclotomicPolynomial<BigVector, BigInteger>(m, modulusQ); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPoly, modulusQ); float stdDev = 4; shared_ptr<ILParams> params(new ILParams(m, modulusQ, rootOfUnity, bigmodulus, bigroot)); BigInteger bigEvalMultModulus("37778931862957161710549"); BigInteger bigEvalMultRootOfUnity("7161758688665914206613"); BigInteger bigEvalMultModulusAlt("1461501637330902918203684832716283019655932547329"); BigInteger bigEvalMultRootOfUnityAlt("570268124029534407621996591794583635795426001824"); auto cycloPolyBig = GetCyclotomicPolynomial<BigVector, BigInteger>(m, bigEvalMultModulus); //ChineseRemainderTransformArb<BigInteger, BigVector>::GetInstance().PreCompute(m, modulusQ); ChineseRemainderTransformArb<BigInteger, BigVector>::SetCylotomicPolynomial(cycloPolyBig, bigEvalMultModulus); PackedIntPlaintextEncoding::SetParams(modulusP, m); usint batchSize = 8; shared_ptr<EncodingParams> encodingParams(new EncodingParams(modulusP, PackedIntPlaintextEncoding::GetAutomorphismGenerator(modulusP), batchSize)); BigInteger delta(modulusQ.DividedBy(modulusP)); //genCryptoContextFV(shared_ptr<typename Element::Params> params, // shared_ptr<typename EncodingParams> encodingParams, // usint relinWindow, float stDev, const std::string& delta, // MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", // int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, // const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0") shared_ptr<CryptoContext<Poly>> cc = CryptoContextFactory<Poly>::genCryptoContextFV(params, encodingParams, 1, stdDev,delta.ToString(),OPTIMIZED, bigEvalMultModulus.ToString(), bigEvalMultRootOfUnity.ToString(),1,9,1.006, bigEvalMultModulusAlt.ToString(), bigEvalMultRootOfUnityAlt.ToString()); cc->Enable(ENCRYPTION); cc->Enable(SHE); // Initialize the public key containers. LPKeyPair<Poly> kp = cc->KeyGen(); vector<shared_ptr<Ciphertext<Poly>>> ciphertext1; vector<shared_ptr<Ciphertext<Poly>>> ciphertext2; vector<shared_ptr<Ciphertext<Poly>>> ciphertextResult; std::vector<usint> vectorOfInts1 = { 1,2,3,4,5,6,7,8,9,10 }; PackedIntPlaintextEncoding intArray1(vectorOfInts1); std::vector<usint> vectorOfInts2 = { 10,9,8,7,6,5,4,3,2,1 }; PackedIntPlaintextEncoding intArray2(vectorOfInts2); std::vector<usint> vectorOfIntsMult; std::transform(vectorOfInts1.begin(), vectorOfInts1.end(), vectorOfInts2.begin(), std::back_inserter(vectorOfIntsMult), std::multiplies<usint>()); ciphertext1 = cc->Encrypt(kp.publicKey, intArray1, false); ciphertext2 = cc->Encrypt(kp.publicKey, intArray2, false); cc->EvalMultKeyGen(kp.secretKey); auto ciphertextMult = cc->EvalMult(ciphertext1.at(0), ciphertext2.at(0)); ciphertextResult.insert(ciphertextResult.begin(), ciphertextMult); PackedIntPlaintextEncoding intArrayNew; cc->Decrypt(kp.secretKey, ciphertextResult, &intArrayNew, false); EXPECT_EQ(intArrayNew, vectorOfIntsMult); }
35.163043
150
0.726306
marcelmon
6e12edfa8a7f3ff1449a60c8383aaea72796e357
1,589
cpp
C++
C++/sum-of-distances-in-tree.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
sum-of-distances-in-tree.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
sum-of-distances-in-tree.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time: O(n) // Space: O(n) class Solution { public: vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) { unordered_map<int, vector<int>> graph; for (const auto& edge : edges) { graph[edge[0]].emplace_back(edge[1]); graph[edge[1]].emplace_back(edge[0]); } vector<int> count(N, 1); vector<int> result(N, 0); dfs(graph, 0, -1, &count, &result); dfs2(graph, 0, -1, &count, &result); return result; } private: void dfs(const unordered_map<int, vector<int>>& graph, int node, int parent, vector<int> *count, vector<int> *result) { if (!graph.count(node)) { return; } for (const auto& nei : graph.at(node)) { if (nei != parent) { dfs(graph, nei, node, count, result); (*count)[node] += (*count)[nei]; (*result)[node] += (*result)[nei] + (*count)[nei]; } } } void dfs2(const unordered_map<int, vector<int>>& graph, int node, int parent, vector<int> *count, vector<int> *result) { if (!graph.count(node)) { return; } for (const auto& nei : graph.at(node)) { if (nei != parent) { (*result)[nei] = (*result)[node] - (*count)[nei] + count->size() - (*count)[nei]; dfs2(graph, nei, node, count, result); } } } };
30.557692
74
0.452486
black-shadows
6e163214b313f7debfbd7fb5f10c545127da76c3
312
hpp
C++
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
36
2018-08-06T13:59:13.000Z
2022-03-25T19:58:58.000Z
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
13
2017-04-03T12:17:27.000Z
2022-02-27T12:17:33.000Z
tests/typedefs.hpp
5cript/interval-tree
27ffeb8e6e8268cb94bd6d5c4f085cf5b595789f
[ "CC0-1.0" ]
5
2019-04-01T15:53:59.000Z
2021-09-15T16:38:32.000Z
#pragma once template <typename ContainedT> struct IntervalTypes { using value_type = ContainedT; using interval_type = lib_interval_tree::interval <ContainedT>; using tree_type = lib_interval_tree::interval_tree <interval_type>; using iterator_type = typename tree_type::iterator; };
28.363636
72
0.746795
5cript
6e223d7642570e8cda894ef8230f867b0e0f5941
2,783
cc
C++
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
src/tck-simulate/graph.cc
schlepil/tchecker
3ab68fe150d16e3db77db8380c47e02026c7815f
[ "MIT" ]
null
null
null
/* * This file is a part of the TChecker project. * * See files AUTHORS and LICENSE for copyright details. * */ #include "graph.hh" namespace tchecker { namespace tck_simulate { /* node_t */ node_t::node_t(tchecker::zg::state_sptr_t const & s) : _state(s) {} node_t::node_t(tchecker::zg::const_state_sptr_t const & s) : _state(s) {} /* edge_t */ edge_t::edge_t(tchecker::zg::transition_t const & t) : _vedge(t.vedge_ptr()) {} /* graph_t */ graph_t::graph_t(std::shared_ptr<tchecker::zg::zg_t> const & zg, std::size_t block_size) : tchecker::graph::reachability::multigraph_t<tchecker::tck_simulate::node_t, tchecker::tck_simulate::edge_t>::multigraph_t( block_size), _zg(zg) { } graph_t::~graph_t() { tchecker::graph::reachability::multigraph_t<tchecker::tck_simulate::node_t, tchecker::tck_simulate::edge_t>::clear(); } void graph_t::attributes(tchecker::tck_simulate::node_t const & n, std::map<std::string, std::string> & m) const { _zg->attributes(n.state_ptr(), m); } void graph_t::attributes(tchecker::tck_simulate::edge_t const & e, std::map<std::string, std::string> & m) const { m["vedge"] = tchecker::to_string(e.vedge(), _zg->system().as_system_system()); } /* DOT output */ /*! \class node_lexical_less_t \brief Less-than order on nodes based on lexical ordering */ class node_lexical_less_t { public: /*! \brief Less-than order on nodes based on lexical ordering \param n1 : a node \param n2 : a node \return true if n1 is less-than n2 w.r.t. lexical ordering over the states in the nodes */ bool operator()(tchecker::tck_simulate::graph_t::node_sptr_t const & n1, tchecker::tck_simulate::graph_t::node_sptr_t const & n2) const { return tchecker::zg::lexical_cmp(n1->state(), n2->state()) < 0; } }; /*! \class edge_lexical_less_t \brief Less-than ordering on edges based on lexical ordering */ class edge_lexical_less_t { public: /*! \brief Less-than ordering on edges based on lexical ordering \param e1 : an edge \param e2 : an edge \return true if e1 is less-than e2 w.r.t. the tuple of edges in e1 and e2 */ bool operator()(tchecker::tck_simulate::graph_t::edge_sptr_t const & e1, tchecker::tck_simulate::graph_t::edge_sptr_t const & e2) const { return tchecker::lexical_cmp(e1->vedge(), e2->vedge()) < 0; } }; std::ostream & dot_output(std::ostream & os, tchecker::tck_simulate::graph_t const & g, std::string const & name) { return tchecker::graph::reachability::dot_output<tchecker::tck_simulate::graph_t, tchecker::tck_simulate::node_lexical_less_t, tchecker::tck_simulate::edge_lexical_less_t>(os, g, name); } } // namespace tck_simulate } // namespace tchecker
28.690722
128
0.679842
schlepil
6e2243f6b58f9a4c6317829b37bef02bec7f500b
6,411
cpp
C++
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
1
2019-12-08T03:53:03.000Z
2019-12-08T03:53:03.000Z
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
182
2018-02-08T11:03:26.000Z
2019-06-27T15:27:47.000Z
ViAn/GUI/viewpathdialog.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
null
null
null
#include "viewpathdialog.h" #include "Project/video.h" #include "viewpathitem.h" #include <QDebug> #include <QDesktopServices> #include <QDialogButtonBox> #include <QFile> #include <QFileDialog> #include <QFormLayout> #include <QHeaderView> #include <QLineEdit> #include <QPushButton> #include <QTreeWidget> #include <QUrl> ViewPathDialog::ViewPathDialog(std::vector<Video*> video_list, QWidget* parent) : QDialog(parent) { setWindowTitle("Vian - View paths"); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose); setMinimumSize(500,200); m_video_list = video_list; QVBoxLayout* v_layout = new QVBoxLayout(this); QHBoxLayout* h_layout = new QHBoxLayout(); path_list = new QTreeWidget(this); path_list->setSelectionMode(QAbstractItemView::ExtendedSelection); path_list->setColumnCount(NUM_COLUMNS); path_list->header()->resizeSection(0,40); path_list->headerItem()->setText(0, "Status"); path_list->headerItem()->setText(1, "Video name"); path_list->headerItem()->setText(2, "Path"); add_paths(path_list); QVBoxLayout* btn_layout = new QVBoxLayout(); btn_layout->setAlignment(Qt::AlignTop); QPushButton* open_folder_btn = new QPushButton(tr("Open folder")); QPushButton* update_path_btn = new QPushButton(tr("Update path")); QPushButton* update_folder_btn = new QPushButton(tr("Update folder")); connect(open_folder_btn, &QPushButton::clicked, this, &ViewPathDialog::open_folder_btn_clicked); connect(update_path_btn, &QPushButton::clicked, this, &ViewPathDialog::update_path_btn_clicked); connect(update_folder_btn, &QPushButton::clicked, this, &ViewPathDialog::update_folder_btn_clicked); btn_layout->addWidget(open_folder_btn); btn_layout->addWidget(update_path_btn); btn_layout->addWidget(update_folder_btn); h_layout->addWidget(path_list); h_layout->addLayout(btn_layout); // Add Buttons btn_box = new QDialogButtonBox; btn_box->addButton(QDialogButtonBox::Ok); btn_box->addButton(QDialogButtonBox::Cancel); connect(btn_box->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &ViewPathDialog::ok_btn_clicked); connect(btn_box->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &ViewPathDialog::cancel_btn_clicked); v_layout->addLayout(h_layout); v_layout->addWidget(btn_box); setLayout(v_layout); } /** * @brief ViewPathDialog::add_paths * Add all videos in the video list to the treewidget * This will set the : * first column with a icon indicating if video can be read * second column with the video name * third column with the video path * @param tree */ void ViewPathDialog::add_paths(QTreeWidget* tree) { for (Video* video : m_video_list) { ViewPathItem* item = new ViewPathItem(video, tree); set_icon(item); } } /** * @brief ViewPathDialog::set_icon * Checks the item's path to see if there is a video file there * Then updates the item's icon to indicate success or failure. * @param item */ void ViewPathDialog::set_icon(ViewPathItem* item) { QFile load_file(item->get_path()); if (load_file.open(QIODevice::ReadOnly)) { // Attempt to open file item->setIcon(0, check_icon); item->set_valid(true); } else { item->setIcon(0, cross_icon); item->set_valid(false); } } /** * @brief ViewPathDialog::all_valid * Returns if all the videopaths are valid * That means the video file in the path can be read. * @return */ bool ViewPathDialog::all_valid() { for (auto i = 0; i < path_list->topLevelItemCount(); ++i) { ViewPathItem* vp_item = dynamic_cast<ViewPathItem*>(path_list->topLevelItem(i)); if (!vp_item->is_valid()) return false; } return true; } /** * @brief ViewPathDialog::open_folder_btn_clicked * Slot function for open_folder button * Open the folder where the selected items is. */ void ViewPathDialog::open_folder_btn_clicked() { if (path_list->selectedItems().length() != 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDesktopServices::openUrl(QUrl("file:///"+v_item->get_dir(), QUrl::TolerantMode)); } /** * @brief ViewPathDialog::update_path_btn_clicked * Slot function for update_path button * Open a dialog where the user can select a new path * where the video is. */ void ViewPathDialog::update_path_btn_clicked() { if (path_list->selectedItems().length() != 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDir standard; standard.mkpath(v_item->get_dir()); QString file_path = QFileDialog::getOpenFileName(this, tr("Choose project path"), v_item->get_dir()); // Update the path for the selected item. if(!file_path.isEmpty()) { v_item->set_path(file_path); set_icon(v_item); } } /** * @brief ViewPathDialog::update_folder_btn_clicked * Slot function for update_folder button * Open a dialog where the user can select a new folder * where the videos are. */ void ViewPathDialog::update_folder_btn_clicked() { // Can be done on multiple items if (path_list->selectedItems().length() < 1) return; auto v_item = dynamic_cast<ViewPathItem*>(path_list->currentItem()); QDir standard; standard.mkpath(v_item->get_dir()); QString new_dir = QFileDialog::getExistingDirectory(this, tr("Choose new directory"), v_item->get_dir()); // Update the directory for all selected items for (auto item : path_list->selectedItems()) { auto v_item = dynamic_cast<ViewPathItem*>(item); if(!new_dir.isEmpty()) { v_item->set_dir(new_dir); set_icon(v_item); } } } /** * @brief ViewPathDialog::ok_btn_clicked * Slot function for ok button */ void ViewPathDialog::ok_btn_clicked() { for (auto item : path_list->findItems("", Qt::MatchContains, 1)) { auto v_item = dynamic_cast<ViewPathItem*>(item); if (v_item->is_item_changed()) { v_item->update_video(); } } accept(); } /** * @brief ViewPathDialog::cancel_btn_clicked * Slot function for cancel button */ void ViewPathDialog::cancel_btn_clicked() { reject(); }
33.046392
121
0.684761
NFCSKL
6e289d4783777cc8b427352df6e1c3245a581215
3,022
hpp
C++
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
OptFrame/Util/TestMove.hpp
vncoelho/optmarket
dcfa8d909da98d89a464eda2420c38b0526f900c
[ "MIT" ]
null
null
null
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef TESTMOVE_HPP_ #define TESTMOVE_HPP_ #include "../Move.hpp" #include <cstdlib> #include <iostream> namespace optframe { template<class R, class ADS = OPTFRAME_DEFAULT_ADS> class TestMove: public Move<R, ADS> { private: static const unsigned long long MAX_MOVE_IN_MEMORY_ERROR = 100000; static unsigned long long MAX_MOVE_IN_MEMORY_WARNING; static unsigned long long testmove_objects; static unsigned long long testmove_objects_nodecrement; unsigned long long testmove_number; public: TestMove() : Move<R, ADS>() { testmove_objects++; testmove_objects_nodecrement++; check(); testmove_number = testmove_objects_nodecrement; } virtual ~TestMove() { testmove_objects--; } void check() // check number of TestMove objects in memory { if (testmove_objects >= MAX_MOVE_IN_MEMORY_WARNING) { cout << "WARNING: " << TestMove<R, ADS>::testmove_objects << " TestMove objects in memory!" << endl; TestMove<R, ADS>::MAX_MOVE_IN_MEMORY_WARNING++; } if (testmove_objects >= MAX_MOVE_IN_MEMORY_ERROR) { cout << "ERROR: " << TestMove<R, ADS>::testmove_objects << " TestMove objects in memory!" << endl; cout << "MAX_MOVE_IN_MEMORY_ERROR = " << MAX_MOVE_IN_MEMORY_ERROR << endl; cout << "aborting..."; exit(1); } } void print() const { cout << "TestMove #" << testmove_number << " (" << testmove_objects << " in memory now): \n"; } TestMove<R, ADS>& operator=(const TestMove<R, ADS>& m) { if (&m == this) // auto ref check return *this; *this = Move<R, ADS>::operator=(m); // do not copy the 'testmove_number' return *this; } Move<R, ADS>& operator=(const Move<R, ADS>& m) { return operator=((const TestMove<R, ADS>&) m); } Move<R, ADS>& clone() const { Move<R, ADS>* m = new TestMove<R, ADS>(*this); return (*m); } }; template<class R, class ADS> unsigned long long TestMove<R, ADS>::MAX_MOVE_IN_MEMORY_WARNING = 0.7 * MAX_MOVE_IN_MEMORY_ERROR; template<class R, class ADS> unsigned long long TestMove<R, ADS>::testmove_objects = 0; template<class R, class ADS> unsigned long long TestMove<R, ADS>::testmove_objects_nodecrement = 0; } #endif /* TESTMOVE_HPP_ */
25.610169
103
0.708471
vncoelho
6e28af1cd0052ffafaaaea019130c799d8d50220
2,718
cpp
C++
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
9
2017-07-03T20:57:53.000Z
2022-03-10T12:19:01.000Z
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
null
null
null
test/matrix_array_test.cpp
muellan/containers
f07c4da2232faac115ff69b05f6d043308b01460
[ "MIT" ]
null
null
null
/***************************************************************************** * * AM utilities * * released under MIT license * * 2008-2017 André Müller * *****************************************************************************/ #include "matrix_array.h" #include <algorithm> #include <numeric> #include <stdexcept> #include <iostream> using namespace am; //------------------------------------------------------------------- void test_initialization() { matrix_array<int,4,3> m1 = { {11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43} }; matrix_array<int,1,3> m2 = {{1,2,3}}; if(!( (m1(0,0) == 11) && (m1(0,1) == 12) && (m1(0,2) == 13) && (m1(1,0) == 21) && (m1(1,1) == 22) && (m1(1,2) == 23) && (m1(2,0) == 31) && (m1(2,1) == 32) && (m1(2,2) == 33) && (m1(3,0) == 41) && (m1(3,1) == 42) && (m1(3,2) == 43) && (m2(0,0) == 1) && (m2(0,1) == 2) && (m2(0,2) == 3) )) { throw std::logic_error("am::matrix initialization"); } } //------------------------------------------------------------------- void test_iterators() { matrix_array<int,7,10> m; std::iota(begin(m), end(m), 11); long long int sum = 0; for(std::size_t j = 0; j < m.rows(); ++j) { for(auto i = m.begin_row(j), e = m.end_row(j); i != e; ++i) { sum += *i; } } sum *= 100; for(std::size_t j = 0; j < m.cols(); ++j) { for(auto i = m.begin_col(j), e = m.end_col(j); i != e; ++i) { sum += *i; } } sum *= 100; for(auto x : m.rectangle(0,0, m.rows()-1, m.cols()-1)) { sum += x; } sum *= 100; for(std::size_t r = 0; r < m.rows(); ++r) { for(std::size_t c = 0; c < m.cols(); ++c) { for(auto x : m.rectangle(0,0, r,c)) { sum += x; } } } for(int r = m.rows()-1; r >= 0; --r) { for(int c = m.cols()-1; c >= 0; --c) { for(auto x : m.rectangle(r,c, m.rows()-1, m.cols()-1)) { sum += x; } } } //diagonal iteration for square matrices { matrix_array<int,10,10> md; std::fill(begin(md), end(md), 0); std::fill(md.begin_diag(), md.end_diag(), 1); sum += std::accumulate(md.begin_diag(), md.end_diag(),0); } if(sum != 3217308650) { throw std::logic_error("am::matrix iteration"); } } //------------------------------------------------------------------- int main() { try { test_initialization(); test_iterators(); } catch(std::exception& e) { std::cerr << e.what(); return 1; } }
22.65
79
0.37454
muellan
6e2a758fd3a6f4f517647b12778d72c42caccd28
724
cc
C++
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
5
2020-04-11T21:30:19.000Z
2021-12-04T16:16:09.000Z
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
suif/lib/suif1/symaddr.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
/* Symbolic Address Implementation */ /* Copyright (c) 1994 Stanford University All rights reserved. This software is provided under the terms described in the "suif_copyright.h" include file. */ #include <suif_copyright.h> #define _MODULE_ "libsuif.a" #pragma implementation "symaddr.h" #define RCS_BASE_FILE symaddr_cc #include "suif1.h" RCS_BASE( "$Id$") void sym_addr::print (FILE *f) { putc('<', f); symbol()->print(f); fprintf(f, ",%d>", offset()); } sym_addr::sym_addr (in_stream *is, base_symtab *symtab) { sym = sym_node::read(is, symtab); off = is->read_int(); } void sym_addr::write (out_stream *os) { symbol()->write(os); os->write_int(offset()); }
15.083333
58
0.649171
paulhjkelly
6e32c57743069fda0ffce21b4fbd2939cde8edbd
5,376
cpp
C++
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
95
2019-02-08T12:22:12.000Z
2019-07-29T06:32:29.000Z
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
73
2019-02-25T18:44:36.000Z
2019-07-02T10:00:45.000Z
compiler/target_benchmark_internals/floyd_benchmark_main.cpp
Ebiroll/floyd
28d05ca4a3a36274cd6e6550eb127739bfde4329
[ "MIT" ]
9
2019-02-19T02:00:22.000Z
2019-07-01T19:10:33.000Z
// // main.cpp // megastruct // // Created by Marcus Zetterquist on 2019-01-28. // Copyright © 2019 Marcus Zetterquist. All rights reserved. // #include "gtest/gtest.h" #include "benchmark/benchmark.h" #include "hardware_caps.h" #include <iostream> #include <vector> //////////////////////////////// BENCHMARK -- GOOGLE EXAMPLES #if 0 int Factorial(int n) { if (n < 0 ) { return 0; } return !n ? 1 : n * Factorial(n - 1); } // IDEA: Only have load/store of entire cache lines. // Tests factorial of 0. TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(Factorial(0), 1); } // Tests factorial of positive numbers. TEST(FactorialTest, HandlesPositiveInput) { EXPECT_EQ(Factorial(1), 1); EXPECT_EQ(Factorial(2), 2); EXPECT_EQ(Factorial(3), 6); EXPECT_EQ(Factorial(8), 40320); } namespace { double CalculatePi(int depth) { double pi = 0.0; for (int i = 0; i < depth; ++i) { double numerator = static_cast<double>(((i % 2) * 2) - 1); double denominator = static_cast<double>((2 * i) - 1); pi += numerator / denominator; } return (pi - 1.0) * 4; } std::set<int64_t> ConstructRandomSet(int64_t size) { std::set<int64_t> s; for (int i = 0; i < size; ++i) s.insert(s.end(), i); return s; } } // end namespace static void BM_Factorial(benchmark::State& state) { int fac_42 = 0; for (auto _ : state) fac_42 = Factorial(8); // Prevent compiler optimizations std::stringstream ss; ss << fac_42; state.SetLabel(ss.str()); } BENCHMARK(BM_Factorial); BENCHMARK(BM_Factorial)->UseRealTime(); static void BM_CalculatePiRange(benchmark::State& state) { double pi = 0.0; for (auto _ : state) pi = CalculatePi(static_cast<int>(state.range(0))); std::stringstream ss; ss << pi; state.SetLabel(ss.str()); } BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); static void BM_CalculatePi(benchmark::State& state) { static const int depth = 1024; for (auto _ : state) { benchmark::DoNotOptimize(CalculatePi(static_cast<int>(depth))); } } BENCHMARK(BM_CalculatePi)->Threads(8); BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); static void BM_SetInsert(benchmark::State& state) { std::set<int64_t> data; for (auto _ : state) { state.PauseTiming(); data = ConstructRandomSet(state.range(0)); state.ResumeTiming(); for (int j = 0; j < state.range(1); ++j) data.insert(rand()); } state.SetItemsProcessed(state.iterations() * state.range(1)); state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int)); } // Test many inserts at once to reduce the total iterations needed. Otherwise, the slower, // non-timed part of each iteration will make the benchmark take forever. BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}}); #endif #if 0 template <typename Container, typename ValueType = typename Container::value_type> static void BM_Sequential(benchmark::State& state) { ValueType v = 42; for (auto _ : state) { Container c; for (int64_t i = state.range(0); --i;) c.push_back(v); } const int64_t items_processed = state.iterations() * state.range(0); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * sizeof(v)); } BENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int) ->Range(1 << 0, 1 << 10); BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10); // Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond. #ifdef BENCHMARK_HAS_CXX11 BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512); #endif static void BM_StringCompare(benchmark::State& state) { size_t len = static_cast<size_t>(state.range(0)); std::string s1(len, '-'); std::string s2(len, '-'); for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2)); } BENCHMARK(BM_StringCompare)->Range(1, 1 << 20); template <class... Args> void BM_with_args(benchmark::State& state, Args&&...) { for (auto _ : state) { } } BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44); BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"), std::pair<int, double>(42, 3.8)); void BM_non_template_args(benchmark::State& state, int, double) { while(state.KeepRunning()) {} } BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); static void BM_DenseThreadRanges(benchmark::State& st) { switch (st.range(0)) { case 1: assert(st.threads == 1 || st.threads == 2 || st.threads == 3); break; case 2: assert(st.threads == 1 || st.threads == 3 || st.threads == 4); break; case 3: assert(st.threads == 5 || st.threads == 8 || st.threads == 11 || st.threads == 14); break; default: assert(false && "Invalid test case number"); } while (st.KeepRunning()) { } } BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3); BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2); BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3); #endif int main(int argc, char** argv) { const auto caps = read_hardware_caps(); const auto caps_string = get_hardware_caps_string(caps); std::cout << caps_string; ::benchmark::Initialize(&argc, argv); if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; ::benchmark::RunSpecifiedBenchmarks(); }
25.722488
90
0.669085
Ebiroll
6e33019fa0d2effc92f96bd80fe19304a566073c
24,638
cpp
C++
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
7
2020-09-07T12:36:42.000Z
2021-07-01T22:15:04.000Z
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
null
null
null
MIRU_CORE/src/directx12/D3D12Image.cpp
AndrewRichards-Code/MIRU
7001830734c7ee0237243e3ab5cd9d2526d3db08
[ "MIT" ]
1
2021-06-11T04:28:57.000Z
2021-06-11T04:28:57.000Z
#include "miru_core_common.h" #if defined(MIRU_D3D12) #include "D3D12Image.h" #include "D3D12Allocator.h" using namespace miru; using namespace d3d12; Image::Image(Image::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; m_ResourceDesc.Dimension = ToD3D12ImageType(m_CI.type); m_ResourceDesc.Alignment = 0; m_ResourceDesc.Width = m_CI.width; m_ResourceDesc.Height = m_CI.height; m_ResourceDesc.DepthOrArraySize = m_CI.type == Image::Type::TYPE_3D ? m_CI.depth : m_CI.arrayLayers; m_ResourceDesc.MipLevels = m_CI.mipLevels; m_ResourceDesc.Format = ToD3D12ImageFormat(m_CI.format); m_ResourceDesc.SampleDesc.Count = static_cast<UINT>(m_CI.sampleCount); m_ResourceDesc.SampleDesc.Quality = 0; m_ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; m_ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE; m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::COLOUR_ATTACHMENT_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAGS(0); m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::DEPTH_STENCIL_ATTACHMENT_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL : D3D12_RESOURCE_FLAGS(0); m_ResourceDesc.Flags |= (bool)(m_CI.usage & Image::UsageBit::STORAGE_BIT) ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAGS(0); D3D12_CLEAR_VALUE clear = {}; bool useClear = false; if (useClear = m_ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { clear.Format = m_ResourceDesc.Format; clear.Color[0] = 0.0f; clear.Color[1] = 0.0f; clear.Color[2] = 0.0f; clear.Color[3] = 0.0f; } if (useClear = m_ResourceDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { clear.Format = m_ResourceDesc.Format; clear.DepthStencil = { 0.0f, 0 }; } D3D12_HEAP_TYPE heapType = ref_cast<Allocator>(m_CI.pAllocator)->GetHeapProperties().Type; if (heapType == D3D12_HEAP_TYPE_DEFAULT) m_InitialResourceState = ToD3D12ImageLayout(m_CI.layout); if (heapType == D3D12_HEAP_TYPE_UPLOAD) m_InitialResourceState = D3D12_RESOURCE_STATE_GENERIC_READ; m_D3D12MAllocationDesc.Flags = D3D12MA::ALLOCATION_FLAG_NONE; m_D3D12MAllocationDesc.HeapType = heapType; m_D3D12MAllocationDesc.ExtraHeapFlags = D3D12_HEAP_FLAG_NONE; m_D3D12MAllocationDesc.CustomPool = nullptr; MIRU_ASSERT(m_CI.pAllocator->GetD3D12MAAllocator()->CreateResource(&m_D3D12MAllocationDesc, &m_ResourceDesc, m_InitialResourceState, useClear ? &clear : nullptr, &m_D3D12MAllocation, IID_PPV_ARGS(&m_Image)), "ERROR: D3D12: Failed to place Image."); D3D12SetName(m_Image, m_CI.debugName); m_Allocation.nativeAllocation = (crossplatform::NativeAllocation)m_D3D12MAllocation; m_Allocation.width = 0; m_Allocation.height = 0; m_Allocation.rowPitch = 0; m_Allocation.rowPadding = 0; if (m_CI.data) { m_CI.pAllocator->SubmitData(m_Allocation, m_CI.size, m_CI.data); } } Image::~Image() { MIRU_CPU_PROFILE_FUNCTION(); if (!m_SwapchainImage) { MIRU_D3D12_SAFE_RELEASE(m_D3D12MAllocation); MIRU_D3D12_SAFE_RELEASE(m_Image); } } void Image::GenerateMipmaps() { } D3D12_RESOURCE_DIMENSION Image::ToD3D12ImageType(Image::Type type) const { MIRU_CPU_PROFILE_FUNCTION(); switch (type) { case Image::Type::TYPE_1D: return D3D12_RESOURCE_DIMENSION_TEXTURE1D; case Image::Type::TYPE_2D: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_3D: return D3D12_RESOURCE_DIMENSION_TEXTURE3D; case Image::Type::TYPE_CUBE: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_1D_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE1D; case Image::Type::TYPE_2D_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Image::Type::TYPE_CUBE_ARRAY: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; default: return D3D12_RESOURCE_DIMENSION_UNKNOWN; } } DXGI_FORMAT Image::ToD3D12ImageFormat(Image::Format format) { MIRU_CPU_PROFILE_FUNCTION(); switch (format) { case Image::Format::UNKNOWN: case Image::Format::R4G4_UNORM_PACK8: case Image::Format::R4G4B4A4_UNORM_PACK16: case Image::Format::B4G4R4A4_UNORM_PACK16: return DXGI_FORMAT_UNKNOWN; case Image::Format::R5G6B5_UNORM_PACK16: case Image::Format::B5G6R5_UNORM_PACK16: return DXGI_FORMAT_B5G6R5_UNORM; case Image::Format::R5G5B5A1_UNORM_PACK16: case Image::Format::B5G5R5A1_UNORM_PACK16: case Image::Format::A1R5G5B5_UNORM_PACK16: return DXGI_FORMAT_B5G5R5A1_UNORM; //R8 case Image::Format::R8_UNORM: return DXGI_FORMAT_R8_UNORM; case Image::Format::R8_SNORM: return DXGI_FORMAT_R8_SNORM; case Image::Format::R8_USCALED: case Image::Format::R8_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8_UINT: return DXGI_FORMAT_R8_UINT; case Image::Format::R8_SINT: return DXGI_FORMAT_R8_SINT; case Image::Format::R8_SRGB: return DXGI_FORMAT_UNKNOWN; //RG8 case Image::Format::R8G8_UNORM: return DXGI_FORMAT_R8G8_UNORM; case Image::Format::R8G8_SNORM: return DXGI_FORMAT_R8G8_SNORM; case Image::Format::R8G8_USCALED: case Image::Format::R8G8_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8_UINT: return DXGI_FORMAT_R8G8_UINT; case Image::Format::R8G8_SINT: return DXGI_FORMAT_R8G8_SINT; case Image::Format::R8G8_SRGB: return DXGI_FORMAT_UNKNOWN; //RGB8 case Image::Format::R8G8B8_UNORM: case Image::Format::B8G8R8_UNORM: case Image::Format::R8G8B8_SNORM: case Image::Format::B8G8R8_SNORM: case Image::Format::R8G8B8_USCALED: case Image::Format::B8G8R8_USCALED: case Image::Format::R8G8B8_SSCALED: case Image::Format::B8G8R8_SSCALED: case Image::Format::R8G8B8_UINT: case Image::Format::B8G8R8_UINT: case Image::Format::R8G8B8_SINT: case Image::Format::B8G8R8_SINT: case Image::Format::R8G8B8_SRGB: case Image::Format::B8G8R8_SRGB: return DXGI_FORMAT_UNKNOWN; //RGBA8 case Image::Format::R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; case Image::Format::B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM; case Image::Format::A8B8G8R8_UNORM_PACK32: return DXGI_FORMAT_R8G8B8A8_UNORM; case Image::Format::R8G8B8A8_SNORM: case Image::Format::B8G8R8A8_SNORM: case Image::Format::A8B8G8R8_SNORM_PACK32: return DXGI_FORMAT_R8G8B8A8_SNORM; case Image::Format::R8G8B8A8_USCALED: case Image::Format::B8G8R8A8_USCALED: case Image::Format::A8B8G8R8_USCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8B8A8_SSCALED: case Image::Format::B8G8R8A8_SSCALED: case Image::Format::A8B8G8R8_SSCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::R8G8B8A8_UINT: case Image::Format::B8G8R8A8_UINT: case Image::Format::A8B8G8R8_UINT_PACK32: return DXGI_FORMAT_R8G8B8A8_UINT; case Image::Format::R8G8B8A8_SINT: case Image::Format::B8G8R8A8_SINT: case Image::Format::A8B8G8R8_SINT_PACK32: return DXGI_FORMAT_R8G8B8A8_SINT; case Image::Format::R8G8B8A8_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; case Image::Format::B8G8R8A8_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; case Image::Format::A8B8G8R8_SRGB_PACK32: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; //RGB10_A2 case Image::Format::A2R10G10B10_UNORM_PACK32: case Image::Format::A2B10G10R10_UNORM_PACK32: return DXGI_FORMAT_R10G10B10A2_UNORM; case Image::Format::A2R10G10B10_SNORM_PACK32: case Image::Format::A2B10G10R10_SNORM_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_USCALED_PACK32: case Image::Format::A2B10G10R10_USCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_SSCALED_PACK32: case Image::Format::A2B10G10R10_SSCALED_PACK32: return DXGI_FORMAT_UNKNOWN; case Image::Format::A2R10G10B10_UINT_PACK32: case Image::Format::A2B10G10R10_UINT_PACK32: return DXGI_FORMAT_R10G10B10A2_UINT; case Image::Format::A2R10G10B10_SINT_PACK32: case Image::Format::A2B10G10R10_SINT_PACK32: return DXGI_FORMAT_UNKNOWN; //R16 case Image::Format::R16_UNORM: return DXGI_FORMAT_R16_UNORM; case Image::Format::R16_SNORM: return DXGI_FORMAT_D16_UNORM; case Image::Format::R16_USCALED: case Image::Format::R16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16_UINT: return DXGI_FORMAT_R16_UINT; case Image::Format::R16_SINT: return DXGI_FORMAT_R16_SINT; case Image::Format::R16_SFLOAT: return DXGI_FORMAT_R16_FLOAT; //RG16 case Image::Format::R16G16_UNORM: return DXGI_FORMAT_R16G16_UNORM; case Image::Format::R16G16_SNORM: return DXGI_FORMAT_R16G16_SNORM; case Image::Format::R16G16_USCALED: case Image::Format::R16G16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16G16_UINT: return DXGI_FORMAT_R16G16_UINT; case Image::Format::R16G16_SINT: return DXGI_FORMAT_R16G16_SINT; case Image::Format::R16G16_SFLOAT: return DXGI_FORMAT_R16G16_FLOAT; //RGB16 case Image::Format::R16G16B16_UNORM: case Image::Format::R16G16B16_SNORM: case Image::Format::R16G16B16_USCALED: case Image::Format::R16G16B16_SSCALED: case Image::Format::R16G16B16_UINT: case Image::Format::R16G16B16_SINT: case Image::Format::R16G16B16_SFLOAT: return DXGI_FORMAT_UNKNOWN; //RGBA16 case Image::Format::R16G16B16A16_UNORM: return DXGI_FORMAT_R16G16B16A16_UNORM; case Image::Format::R16G16B16A16_SNORM: return DXGI_FORMAT_R16G16B16A16_SNORM; case Image::Format::R16G16B16A16_USCALED: case Image::Format::R16G16B16A16_SSCALED: return DXGI_FORMAT_UNKNOWN; case Image::Format::R16G16B16A16_UINT: return DXGI_FORMAT_R16G16B16A16_UINT; case Image::Format::R16G16B16A16_SINT: return DXGI_FORMAT_R16G16B16A16_SINT; case Image::Format::R16G16B16A16_SFLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; //R32 case Image::Format::R32_UINT: return DXGI_FORMAT_R32_UINT; case Image::Format::R32_SINT: return DXGI_FORMAT_R32_SINT; case Image::Format::R32_SFLOAT: return DXGI_FORMAT_R32_FLOAT; //RG32 case Image::Format::R32G32_UINT: return DXGI_FORMAT_R32G32_UINT; case Image::Format::R32G32_SINT: return DXGI_FORMAT_R32G32_SINT; case Image::Format::R32G32_SFLOAT: return DXGI_FORMAT_R32G32_FLOAT; //RGB32 case Image::Format::R32G32B32_UINT: return DXGI_FORMAT_R32G32B32_UINT; case Image::Format::R32G32B32_SINT: return DXGI_FORMAT_R32G32B32_SINT; case Image::Format::R32G32B32_SFLOAT: return DXGI_FORMAT_R32G32B32_FLOAT; //RGBA32 case Image::Format::R32G32B32A32_UINT: return DXGI_FORMAT_R32G32B32A32_UINT; case Image::Format::R32G32B32A32_SINT: return DXGI_FORMAT_R32G32B32A32_SINT; case Image::Format::R32G32B32A32_SFLOAT: return DXGI_FORMAT_R32G32B32A32_FLOAT; //R64, RG64, RGB64, RGBA64 case Image::Format::R64_UINT: case Image::Format::R64_SINT: case Image::Format::R64_SFLOAT: case Image::Format::R64G64_UINT: case Image::Format::R64G64_SINT: case Image::Format::R64G64_SFLOAT: case Image::Format::R64G64B64_SINT: case Image::Format::R64G64B64_SFLOAT: case Image::Format::R64G64B64A64_UINT: case Image::Format::R64G64B64A64_SINT: case Image::Format::R64G64B64A64_SFLOAT: return DXGI_FORMAT_UNKNOWN; case Image::Format::B10G11R11_UFLOAT_PACK32: return DXGI_FORMAT_R11G11B10_FLOAT; case Image::Format::E5B9G9R9_UFLOAT_PACK32: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP; case Image::Format::D16_UNORM: return DXGI_FORMAT_D16_UNORM; case Image::Format::X8_D24_UNORM_PACK32: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; case Image::Format::D32_SFLOAT: return DXGI_FORMAT_D32_FLOAT; case Image::Format::S8_UINT: return DXGI_FORMAT_R8_UINT; case Image::Format::D16_UNORM_S8_UINT: return DXGI_FORMAT_UNKNOWN; case Image::Format::D24_UNORM_S8_UINT: return DXGI_FORMAT_D24_UNORM_S8_UINT; case Image::Format::D32_SFLOAT_S8_UINT: return DXGI_FORMAT_UNKNOWN; default: return DXGI_FORMAT_UNKNOWN; } } D3D12_RESOURCE_STATES Image::ToD3D12ImageLayout(Image::Layout layout) { MIRU_CPU_PROFILE_FUNCTION(); switch (layout) { case Image::Layout::UNKNOWN: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::GENERAL: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::COLOUR_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_RENDER_TARGET; case Image::Layout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_WRITE; case Image::Layout::DEPTH_STENCIL_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::SHADER_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; case Image::Layout::TRANSFER_SRC_OPTIMAL: return D3D12_RESOURCE_STATE_COPY_SOURCE; case Image::Layout::TRANSFER_DST_OPTIMAL: return D3D12_RESOURCE_STATE_COPY_DEST; case Image::Layout::PREINITIALIZED: return D3D12_RESOURCE_STATE_COMMON; case Image::Layout::DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_DEPTH_READ; case Image::Layout::PRESENT_SRC: return D3D12_RESOURCE_STATE_PRESENT; case Image::Layout::SHARED_PRESENT: return D3D12_RESOURCE_STATE_PRESENT; case Image::Layout::D3D12_RESOLVE_SOURCE: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case Image::Layout::D3D12_RESOLVE_DEST: return D3D12_RESOURCE_STATE_RESOLVE_DEST; case Image::Layout::D3D12_UNORDERED_ACCESS: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; case Image::Layout::D3D12_NON_PIXEL_SHADER_READ_ONLY_OPTIMAL: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; default: return D3D12_RESOURCE_STATE_COMMON; } } ImageView::ImageView(ImageView::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; D3D12_RESOURCE_DESC resourceDesc = ref_cast<Image>(m_CI.pImage)->m_ResourceDesc; ID3D12Resource* image = ref_cast<Image>(m_CI.pImage)->m_Image; //RTV { m_RTVDesc.Format = resourceDesc.Format; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D; m_RTVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS; break; } else { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; m_RTVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; m_RTVDesc.Texture2D.PlaneSlice = 0; break; } } case Image::Type::TYPE_3D: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; m_RTVDesc.Texture3D.FirstWSlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture3D.WSize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture3D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_1D_ARRAY: { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY; m_RTVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; m_RTVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; m_RTVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_RTVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_RTVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; m_RTVDesc.Texture2DArray.PlaneSlice = 0; break; } } } } //DSV if(ref_cast<Image>(m_CI.pImage)->GetCreateInfo().format >= Image::Format::D16_UNORM) { m_DSVDesc.Format = resourceDesc.Format; m_DSVDesc.Flags = D3D12_DSV_FLAG_NONE; //D3D12_DSV_FLAG_READ_ONLY_DEPTH | D3D12_DSV_FLAG_READ_ONLY_STENCIL; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1D; m_DSVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMS; break; } else { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; m_DSVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } } case Image::Type::TYPE_1D_ARRAY: { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE1DARRAY; m_DSVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_DSVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_3D: case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; m_DSVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_DSVDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; m_DSVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_DSVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_DSVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } } } } //SRV { m_SRVDesc.Format = resourceDesc.Format; m_SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; m_SRVDesc.Texture1D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture1D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture1D.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_2D: { if (resourceDesc.SampleDesc.Count > 1) { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; break; } else { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; m_SRVDesc.Texture2D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture2D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture2D.PlaneSlice = 0; m_SRVDesc.Texture2D.ResourceMinLODClamp = 0.0f; break; } } case Image::Type::TYPE_3D: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; m_SRVDesc.Texture3D.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture3D.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture3D.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_CUBE: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; m_SRVDesc.TextureCube.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.TextureCube.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.TextureCube.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_1D_ARRAY: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; m_SRVDesc.Texture1DArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture1DArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_SRVDesc.Texture1DArray.ResourceMinLODClamp = 0.0f; break; } case Image::Type::TYPE_2D_ARRAY: { if (resourceDesc.SampleDesc.Count > 1) { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; m_SRVDesc.Texture2DMSArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture2DMSArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; break; } else { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; m_SRVDesc.Texture2DArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.Texture2DArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_SRVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_SRVDesc.Texture2DArray.PlaneSlice = 0; m_SRVDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; break; } } case Image::Type::TYPE_CUBE_ARRAY: { m_SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; m_SRVDesc.TextureCubeArray.MostDetailedMip = m_CI.subresourceRange.baseMipLevel; m_SRVDesc.TextureCubeArray.MipLevels = m_CI.subresourceRange.mipLevelCount; m_SRVDesc.TextureCubeArray.First2DArrayFace = 0; m_SRVDesc.TextureCubeArray.NumCubes = resourceDesc.DepthOrArraySize / 6; m_SRVDesc.TextureCubeArray.ResourceMinLODClamp = 0.0f; break; } } } //UAV { m_UAVDesc.Format = resourceDesc.Format; switch (m_CI.viewType) { case Image::Type::TYPE_1D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; m_UAVDesc.Texture1D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_2D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; m_UAVDesc.Texture2D.MipSlice = m_CI.subresourceRange.baseMipLevel; m_UAVDesc.Texture2D.PlaneSlice = 0; break; } case Image::Type::TYPE_3D: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; m_UAVDesc.Texture3D.FirstWSlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture3D.WSize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture3D.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_1D_ARRAY: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; m_UAVDesc.Texture1DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture1DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture1DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; break; } case Image::Type::TYPE_CUBE: case Image::Type::TYPE_CUBE_ARRAY: case Image::Type::TYPE_2D_ARRAY: { m_UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; m_UAVDesc.Texture2DArray.FirstArraySlice = m_CI.subresourceRange.baseArrayLayer; m_UAVDesc.Texture2DArray.ArraySize = m_CI.subresourceRange.arrayLayerCount; m_UAVDesc.Texture2DArray.MipSlice = m_CI.subresourceRange.baseMipLevel; m_UAVDesc.Texture2DArray.PlaneSlice = 0; break; } } } } ImageView::~ImageView() { MIRU_CPU_PROFILE_FUNCTION(); } Sampler::Sampler(Sampler::CreateInfo* pCreateInfo) :m_Device(reinterpret_cast<ID3D12Device*>(pCreateInfo->device)) { MIRU_CPU_PROFILE_FUNCTION(); m_CI = *pCreateInfo; m_SamplerDesc.Filter = ToD3D12Filter(m_CI.magFilter, m_CI.minFilter, m_CI.mipmapMode, m_CI.anisotropyEnable); m_SamplerDesc.AddressU = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeU) + 1); m_SamplerDesc.AddressV = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeV) + 1); m_SamplerDesc.AddressW = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(static_cast<uint32_t>(m_CI.addressModeW) + 1); m_SamplerDesc.MipLODBias = m_CI.mipLodBias; m_SamplerDesc.MaxAnisotropy = static_cast<UINT>(m_CI.maxAnisotropy); m_SamplerDesc.ComparisonFunc = static_cast<D3D12_COMPARISON_FUNC>(static_cast<uint32_t>(m_CI.compareOp) + 1); m_SamplerDesc.BorderColor[0] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[1] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[2] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_WHITE ? 0.0f : 1.0f; m_SamplerDesc.BorderColor[3] = m_CI.borderColour < BorderColour::FLOAT_OPAQUE_BLACK ? 0.0f : 1.0f; m_SamplerDesc.MinLOD = m_CI.minLod; m_SamplerDesc.MaxLOD = m_CI.maxLod; } Sampler::~Sampler() { MIRU_CPU_PROFILE_FUNCTION(); } D3D12_FILTER Sampler::ToD3D12Filter(Filter magFilter, Filter minFilter, MipmapMode mipmapMode, bool anisotropic) { MIRU_CPU_PROFILE_FUNCTION(); if (anisotropic) return D3D12_FILTER_ANISOTROPIC; uint32_t res = 0; if (mipmapMode == MipmapMode::LINEAR) res += 1; if (magFilter == Filter::LINEAR) res += 4; if (minFilter == Filter::LINEAR) res += 16; return static_cast<D3D12_FILTER>(res); } #endif
34.362622
249
0.79073
AndrewRichards-Code
6e37eb70713a8a61a8dd0019b40bf278c8943fdc
3,098
cpp
C++
codeforces/round698_div2/c.cpp
zaurus-yusya/atcoder
5fc345b3da50222fa1366d1ce52ae58799488cef
[ "MIT" ]
3
2020-05-27T16:27:12.000Z
2021-01-27T12:47:12.000Z
codeforces/round698_div2/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
codeforces/round698_div2/c.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> // #include <atcoder/all> // using namespace atcoder; typedef long long ll; typedef long double ld; #define rep(i,n) for(ll i=0;i<(n);i++) #define repr(i,n) for(ll i=(n-1);i>=0;i--) #define all(x) x.begin(),x.end() #define br cout << "\n"; using namespace std; const long long INF = 1e18; const long long MOD = 1e9+7; using Graph = vector<vector<ll>>; using pll = pair<ll, ll>; template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;} template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;} ll ceilll(ll a, ll b) {return (a + b-1) / b;} // if(a%b != 0) (a/b) + 1 ll get_digit(ll a) {ll digit = 0; while(a != 0){a /= 10; digit++;} return digit;} // a != 0 template<typename T> void vecdbg(vector<T>& v){ rep(i, v.size()){cout << v[i] << " ";} br;} template<typename T> void vecvecdbg(vector<vector<T>>& v){ rep(i, v.size()){rep(j, v[i].size()){cout << v[i][j] << " ";} br;}} // 0 false, 1 true // string number to int : -48 // a to A : -32 // ceil(a) 1.2->2.0 // c++17 g++ -std=c++17 a.cpp // global vector -> 0 initialization // DONT FORGET TO INTIALIZE // The type of GRID is CHAR. DONT USE STRING // If the result in local and judge is different, USE CODETEST!! int main() { std::cout << std::fixed << std::setprecision(15); ll t; cin >> t; rep(T, t){ ll n; cin >> n; vector<long long> d(2 * n); vector<ll> sum(2 * n + 1); map<ll, ll> mp; bool flag = true; for(long long i = 0; i < 2 * n; i ++){ cin >> d[i]; if(d[i] % 2 == 1) flag = false; mp[d[i]]++; } sort(all(d), greater<ll>()); rep(i, 2*n){ sum[i+1] = sum[i] + d[i]; } vecdbg(d); vecdbg(sum); cout << "---" << endl; for(ll i = 0; i < 2 * n; i++){ //cout << ( sum[i] - sum[0] - (i * d[i]) ) << " " << ( (2*n-i-1)*d[i] - (sum[2*n] - sum[i+1])) <<endl; cout << ( sum[i] - sum[0] - (i * d[i]) ) + ( (2*n-i-1)*d[i] - (sum[2*n] - sum[i+1])) <<endl; } cout << "---" << endl; vector<ll> sa; ll now = 0; ll res = 0; bool flag2 = false; for(auto i: mp){ if(flag2){ sa.push_back(i.first - now); now = i.first; res = i.first; }else{ flag2 = true; now = i.first; } /* now = i.first; cout << i.first << " " << i.second << endl; */ } vecdbg(sa); string ans = "YES"; ll tmp = 1, tmp2 = 1; ll cur = 2; rep(i, sa.size()){ if(sa[i] % cur != 0){ ans = "NO"; } tmp2 = tmp2 + sa[i] / cur; tmp += tmp2; cur += 2; } cout << tmp << " " << res << endl; if(tmp > (res/2)){ ans = "NO"; } cout << ans << endl; } }
29.504762
126
0.433505
zaurus-yusya
6e3a00efcd6c178ce51b193d1565a185e01052da
1,461
cpp
C++
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
test/datastore/TestCacheMap.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
#include <pulsar/testing/CppTester.hpp> #include <pulsar/datastore/CacheMap.hpp> using namespace pulsar; using namespace std; TEST_SIMPLE(TestCacheMap){ CppTester tester("Testing CacheMap class"); CacheMap cm1; using Vector=vector<double>; Vector v1({1.0,2.0,3.0}),v2({2.0,3.0,4.0}); const std::string key="Vector1",not_key="Not A key"; unsigned int policy=CacheMap::NoPolicy; cm1.set(key,v1,policy); const set<string> keys({key}); tester.test_member_return("get_keys",true,keys,&CacheMap::get_keys,&cm1); shared_ptr<const int> pi; tester.test_member_return("get w/non-existent key",true,pi,&CacheMap::get<int>,&cm1,not_key,false); auto pj=cm1.get<Vector>(key,false); tester.test_equal("get_w/real key",v1,*pj); tester.test_member_return("size",true,1,&CacheMap::size,&cm1); cm1.set(key,v2,policy); pj=cm1.get<Vector>(key,false); tester.test_equal("set overwrote",v2,*pj); tester.test_member_call("erase w/non-existent key",true,&CacheMap::erase,&cm1,not_key); tester.test_member_return("erase did nothing",true,1,&CacheMap::size,&cm1); tester.test_member_call("erase w/real key",true,&CacheMap::erase,&cm1,key); tester.test_member_return("erased",true,0,&CacheMap::size,&cm1); tester.test_member_call("clear",true,&CacheMap::clear,&cm1); tester.test_member_return("cleared",true,0,&CacheMap::size,&cm1); tester.print_results(); return tester.nfailed(); }
39.486486
103
0.704997
pulsar-chem
6e437318383671d2e835f4141ae32a3690d524d9
1,066
hpp
C++
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
inc/cxpr_swap.hpp
TinfoilPancakes/hilbert-generator
e53ce260e3e998d0c1e92e6e2165c0c0a347aa81
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* __ */ /* cxpr_swap.hpp <(o )___ */ /* ( ._> / - Weh. */ /* By: prp <[email protected]> --`---'------------- */ /* 54 69 6E 66 6F 69 6C */ /* Created: 2020/09/11 16:09:39 by prp 2E 54 65 63 68 */ /* Updated: 2020/09/13 23:48:09 by prp 50 2E 52 2E 50 */ /* */ /* ************************************************************************** */ #ifndef CXPR_SWAP_HPP #define CXPR_SWAP_HPP template <typename T> constexpr void cxpr_swap( T&& a, T&& b ) { auto tmp = a; a = b; b = tmp; } #endif
48.454545
80
0.212946
TinfoilPancakes
6e4bc35de6fb436d3f18646d12cf5f5e23d24710
6,760
cpp
C++
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
null
null
null
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
2
2019-06-11T16:46:56.000Z
2020-06-11T13:26:51.000Z
d3d10drv/texturecache.cpp
SuiMachine/khg-d3d10drv
58235d94440791f63abca857584bd2f06c963d60
[ "MIT" ]
1
2021-09-27T09:54:57.000Z
2021-09-27T09:54:57.000Z
/** Cache for game textures; also handles the external extra textures. */ #include "texturecache.h" #include "d3d10drv.h" //Definitions of extra external textures const TextureCache::ExternalTexture TextureCache::externalTextures[TextureCache::DUMMY_NUM_EXTERNAL_TEXTURES] = {{".detail",1},{".bump",0},{".height",0}}; TextureCache::TextureCache(ID3D10Device *device) { this->device = device; } /** Create a texture from a descriptor and data to fill it with. \param desc Direct3D texture description. \param data Data to fill the texture with. */ ID3D10Texture2D *TextureCache::createTexture(const D3D10_TEXTURE2D_DESC &desc,const D3D10_SUBRESOURCE_DATA &data) const { //Creates a texture, setting the TextureInfo's data member. HRESULT hr; ID3D10Texture2D *texture; hr=device->CreateTexture2D(&desc,&data, &texture); if(FAILED(hr)) { UD3D10RenderDevice::debugs("Error creating texture resource."); return nullptr; } return texture; } /** Update a single texture mip using a copy operation. \param id CacheID to insert texture with. \param mipNum Mip level to update. \param data Data to write to the mip. */ void TextureCache::updateMip(const FTextureInfo& Info,int mipNum,const D3D10_SUBRESOURCE_DATA &data) const { //If texture is currently bound, draw buffers before updating for(int i=0;i<TextureCache::DUMMY_NUM_TEXTURE_PASSES;i++) { if(texturePasses.boundTextureID[i]==Info.CacheID) { D3D::render(); break; } } //Update const auto& entry = textureCache.find(Info.CacheID)->second; //device->UpdateSubresource(entry.texture,mipNum,nullptr,(void*) data.pSysMem,data.SysMemPitch,data.SysMemSlicePitch); //UpdateSubResource leads to flickering on nvidia D3D10_MAPPED_TEXTURE2D Mapping; entry.texture->Map(mipNum,D3D10_MAP_WRITE_DISCARD,0,&Mapping); unsigned char* pDst = static_cast<unsigned char*>(Mapping.pData); const unsigned char* pSrc = static_cast<const unsigned char*>(data.pSysMem); for (int y = 0; y < Info.VClamp; y++) { memcpy(pDst, pSrc, Info.UClamp*sizeof(DWORD)>>mipNum); pSrc += data.SysMemPitch; pDst += Mapping.RowPitch; } entry.texture->Unmap(mipNum); } /** Load a texture from a .dds file \return true when succesful */ bool TextureCache::loadFileTexture(TCHAR* fileName, ID3D10Texture2D **tex, D3DX10_IMAGE_LOAD_INFO *loadInfo) const { HRESULT hr; hr = D3DX10CreateTextureFromFile(device, fileName, loadInfo, nullptr, (ID3D10Resource** )tex, nullptr); if(FAILED(hr)) return false; return true; } /** Create a resource view (texture usable by shader) from a filled-in texture and cache it. Caller can then release the texture. \param id CacheID to insert texture with. \param metadata Texture metadata. \param tex A filled Direct3D texture. \param extraIndex Index of the extra external texture slot to use (optional) */ void TextureCache::cacheTexture(unsigned __int64 id,const TextureMetaData &metadata, ID3D10Texture2D *tex, int extraIndex) { HRESULT hr; D3D10_TEXTURE2D_DESC desc; tex->GetDesc(&desc); //Create resource view ID3D10ShaderResourceView* r; D3D10_SHADER_RESOURCE_VIEW_DESC srDesc; srDesc.Format = desc.Format; srDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srDesc.Texture2D.MostDetailedMip = 0; srDesc.Texture2D.MipLevels = desc.MipLevels; hr = device->CreateShaderResourceView(tex,&srDesc,&r); if(FAILED(hr)) { UD3D10RenderDevice::debugs("Error creating texture shader resource view."); return; } //Cache texture if(extraIndex==-1) { CachedTexture c; c.metadata = metadata; tex->AddRef(); c.texture = tex; c.resourceView = r; for(int i=0;i<DUMMY_NUM_EXTERNAL_TEXTURES;i++) { c.externalTextures[i]=nullptr; } textureCache[id]=c; } else //add extra texture { CachedTexture *c = &textureCache[id]; c->externalTextures[extraIndex] = r; c->metadata.externalTextures[extraIndex]=true; } } /** Returns true if texture is in cache. \param id CacheID for texture. */ bool TextureCache::textureIsCached(DWORD64 id) const { return textureCache.find(id) != textureCache.end(); } /** Returns texture metadata. \param id CacheID for texture. */ const TextureCache::TextureMetaData &TextureCache::getTextureMetaData(DWORD64 id) const { return textureCache.find(id)->second.metadata; } /** Set the texture for a texture pass (diffuse, lightmap, etc). Texture is only set if it's not already the current one for that pass. Cached polygons (using the previous set of textures) are drawn before the switch is made. \param id CacheID for texture. NULL sets no texture for the pass (by disabling it using a shader constant). \param extraIndex Index of the extra external texture slot to use (optional), -1 for none. \return texture metadata so renderer can use parameters such as scale/pan; NULL is texture not found */ const TextureCache::TextureMetaData *TextureCache::setTexture(const Shader_Unreal* shader,TexturePass pass,DWORD64 id, int extraIndex) { static TextureMetaData *metadata[DUMMY_NUM_TEXTURE_PASSES]; //Cache this so it can even be returned when no texture was actually set (because same id as last time) if(id!=texturePasses.boundTextureID[pass]) //If different texture than previous one, draw geometry in buffer and switch to new texture { texturePasses.boundTextureID[pass]=id; D3D::render(); //Turn on and switch to new texture CachedTexture *tex; if(!textureIsCached(id)) //Texture not in cache, conversion probably went wrong. return nullptr; tex = &textureCache[id]; if(extraIndex==-1) shader->setTexture(pass,tex->resourceView); else shader->setTexture(pass,tex->externalTextures[extraIndex]); metadata[pass] = &tex->metadata; } return metadata[pass]; } /** Delete a texture (so it can be overwritten with an updated one). */ void TextureCache::deleteTexture(DWORD64 id) { std::unordered_map<DWORD64,CachedTexture>::iterator i = textureCache.find(id); if(i==textureCache.end()) return; SAFE_RELEASE(i->second.texture); SAFE_RELEASE(i->second.resourceView); for(int j=0;j<DUMMY_NUM_EXTERNAL_TEXTURES;j++) { SAFE_RELEASE(i->second.externalTextures[j]); } textureCache.erase(i); } /** Clear texture cache. */ void TextureCache::flush() { //Clear bindings so textures will be rebound after flush for(int i=0;i<DUMMY_NUM_TEXTURE_PASSES;i++) { texturePasses.boundTextureID[i]=0; } //Delete textures for(std::unordered_map<DWORD64,CachedTexture>::iterator i=textureCache.begin();i!=textureCache.end();i++) { while(i->second.resourceView) { SAFE_RELEASE(i->second.resourceView); } while(i->second.texture) { SAFE_RELEASE(i->second.texture); } for(int j=0;j<DUMMY_NUM_EXTERNAL_TEXTURES;j++) { SAFE_RELEASE(i->second.externalTextures[j]); } } textureCache.clear(); }
27.479675
165
0.744527
SuiMachine
6e4d53110d855e9f2bb81c97891cd90e71655e9e
15,076
cpp
C++
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
gem/Code/Source/Components/AlarmComponent.cpp
loherangrin/addons.o3de.date-time
e3e7719204490dc2b69598e88803aaa1b3bb4fa3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Matteo Grasso * * 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 <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/SerializeContext.h> #include <DateTime/Constants/DateTimeConstants.hpp> #include "../Types/Alarm.hpp" #include "AlarmComponent.hpp" using Loherangrin::Gems::DateTime::Date; using Loherangrin::Gems::DateTime::Time; using Loherangrin::Gems::DateTime::AlarmId; using Loherangrin::Gems::DateTime::AlarmComponent; namespace Loherangrin::Gems::DateTime { class AlarmComponentEventHandler : public AZ::SerializeContext::IEventHandler { void OnWriteEnd(void* io_classPtr) { auto* alarmComponent = reinterpret_cast<AlarmComponent*>(io_classPtr); alarmComponent->CancelAllAlarms(); alarmComponent->AddAlarmsFromConfig(alarmComponent->m_config.m_alarms); } }; class AlarmNotificationBusBehaviorHandler : public AlarmNotificationBus::Handler , public AZ::BehaviorEBusHandler { public: AZ_EBUS_BEHAVIOR_BINDER(AlarmNotificationBusBehaviorHandler, "{4E736648-7F9A-493A-811C-95AD6E855231}", AZ::SystemAllocator, OnAlarmBell ); void OnAlarmBell(const Date& i_date, const Time& i_time) override { Call(FN_OnAlarmBell, i_date, i_time); } }; } // Loherangrin::Gems::DateTime void AlarmComponent::Reflect(AZ::ReflectContext* io_context) { ConfigClass::Reflect(io_context); if(auto serializeContext = azrtti_cast<AZ::SerializeContext*>(io_context)) { serializeContext->Class<AlarmComponent, AZ::Component>() ->Version(0) ->EventHandler<AlarmComponentEventHandler>() ->Field("Configuration", &AlarmComponent::m_config) ; } if(auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(io_context)) { behaviorContext->EBus<AlarmRequestBus>("AlarmRequestBus") ->Attribute(AZ::Script::Attributes::Module, ScriptAttributes::MODULE) ->Attribute(AZ::Script::Attributes::Category, ScriptAttributes::CATEGORY) ->Event<AlarmId (AlarmRequestBus::Events::*)(const DateRecurrenceRuleBehaviorHandle&, const TimeRecurrenceRuleBehaviorHandle&, const AZ::EntityId&)>("SetAlarmToNotify", &AlarmRequestBus::Events::SetAlarmToNotify) ->Event("CancelAlarm", &AlarmRequestBus::Events::CancelAlarm) ->Event("CancelAllAlarms", &AlarmRequestBus::Events::CancelAllAlarms) ->Event("SilenceAlarm", &AlarmRequestBus::Events::SilenceAlarm) ->Event("SilenceAllAlarms", &AlarmRequestBus::Events::SilenceAllAlarms) ->Event("GetWhenNextAlarm", &AlarmRequestBus::Events::GetWhenNextAlarm) ->Event("GetNextAlarmDate", &AlarmRequestBus::Events::GetNextAlarmDate) ->Event("GetNextAlarmTime", &AlarmRequestBus::Events::GetNextAlarmTime) ; behaviorContext->EBus<AlarmNotificationBus>("AlarmNotificationBus") ->Attribute(AZ::Script::Attributes::Module, ScriptAttributes::MODULE) ->Attribute(AZ::Script::Attributes::Category, ScriptAttributes::CATEGORY) ->Handler<AlarmNotificationBusBehaviorHandler>() ; } } void AlarmComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& io_provided) { io_provided.push_back(Services::ALARM); } void AlarmComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& io_incompatible) { io_incompatible.push_back(Services::ALARM); } void AlarmComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& io_required) { io_required.push_back(Services::TIME); } void AlarmComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& io_dependent) { io_dependent.push_back(Services::DATE); } AlarmComponent::AlarmComponent() : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config {} {} AlarmComponent::AlarmComponent(const ConfigClass& i_config) : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config { i_config } { AddAlarmsFromConfig(m_config.m_alarms); } AlarmComponent::AlarmComponent(ConfigClass&& io_config) : m_isReversedTime { false } , m_alarmPrioritizer { m_isReversedTime } , m_allAlarms {} , m_orderedAlarms { m_alarmPrioritizer } , m_nowDate {} , m_config { AZStd::move(io_config) } { AddAlarmsFromConfig(m_config.m_alarms); } void AlarmComponent::Init() {} void AlarmComponent::Activate() { SynchronizeWithDateAndTimeComponents(); DateNotificationBus::Handler::BusConnect(); TimeNotificationBus::Handler::BusConnect(); AlarmRequestBus::Handler::BusConnect(); } void AlarmComponent::Deactivate() { AlarmRequestBus::Handler::BusDisconnect(); TimeNotificationBus::Handler::BusDisconnect(); DateNotificationBus::Handler::BusDisconnect(); } void AlarmComponent::OnDateDayChanged(const Date& i_nowDate) { m_nowDate = i_nowDate; } void AlarmComponent::OnDateReset(const Date& i_startDate) { m_nowDate = i_startDate; Time nowTime = GetCurrentTime(); ResetAlarms(nowTime); } void AlarmComponent::OnTimeSecondChanged(const Time& i_nowTime) { ProcessAlarms(i_nowTime); } void AlarmComponent::OnTimeSpeedChanged(float i_speed) { bool changed = CalculateTimeDirection(i_speed); if(!changed) { return; } Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); if(nowTime.IsValid()) { ResetAlarms(nowTime); } } void AlarmComponent::OnTimeReset(const Time& i_startTime) { ResetAlarms(i_startTime); } AlarmId AlarmComponent::SetAlarmToExecute(const DateRecurrenceRule& i_dateRule, const TimeRecurrenceRule& i_timeRule, const AlarmCallback& i_callback) { Time nowTime = GetCurrentTime(); AlarmHandle alarmHandle = Alarm::CreateInstance(i_dateRule, i_timeRule, i_callback); const AlarmId alarmId = AddAlarm(AZStd::move(alarmHandle), nowTime); return alarmId; } AlarmId AlarmComponent::SetAlarmToNotify(const DateRecurrenceRule& i_dateRule, const TimeRecurrenceRule& i_timeRule, const AZ::EntityId& i_requesterId) { Time nowTime = GetCurrentTime(); AlarmHandle alarmHandle = Alarm::CreateInstance(i_dateRule, i_timeRule, i_requesterId); const AlarmId alarmId = AddAlarm(AZStd::move(alarmHandle), nowTime); return alarmId; } AlarmId AlarmComponent::SetAlarmToNotify(const DateRecurrenceRuleBehaviorHandle& i_dateRuleHandle, const TimeRecurrenceRuleBehaviorHandle& i_timeRuleHandle, const AZ::EntityId& i_requester) { const DateRecurrenceRule* dateRule = i_dateRuleHandle.GetRule(); const TimeRecurrenceRule* timeRule = i_timeRuleHandle.GetRule(); if(!dateRule || !timeRule) { AZ_Assert(false, "Recurrence rule cannot be null"); return 0; } return SetAlarmToNotify(*dateRule, *timeRule, i_requester); } bool AlarmComponent::CancelAlarm(AlarmId i_alarmId) { auto result = m_allAlarms.find(Alarm::CreateEmpty(i_alarmId)); if(result == m_allAlarms.end()) { return false; } Alarm* alarm = result->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Cancel(); return true; } void AlarmComponent::CancelAllAlarms() { m_orderedAlarms = AlarmQueue { m_alarmPrioritizer }; m_allAlarms.clear(); } bool AlarmComponent::SilenceAlarm(AlarmId i_alarmId, bool i_silent) { auto result = m_allAlarms.find(Alarm::CreateEmpty(i_alarmId)); if(result == m_allAlarms.end()) { return false; } Alarm* alarm = result->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Silence(i_silent); return true; } void AlarmComponent::SilenceAllAlarms(bool i_silent) { for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Silence(i_silent); } } AZStd::pair<Date, Time> AlarmComponent::GetWhenNextAlarm() const { if(m_orderedAlarms.empty()) { return AZStd::make_pair(Date {}, Time {}); } AlarmHandle* const alarmHandle = m_orderedAlarms.top(); Alarm* alarm = alarmHandle->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); return AZStd::make_pair(alarm->GetDate(), alarm->GetTime()); } Date AlarmComponent::GetNextAlarmDate() const { AZStd::pair<Date, Time> nextAlarm = GetWhenNextAlarm(); return nextAlarm.first; } Time AlarmComponent::GetNextAlarmTime() const { AZStd::pair<Date, Time> nextAlarm = GetWhenNextAlarm(); return nextAlarm.second; } bool AlarmComponent::DiscardPastAlarmRepeats(Alarm& io_alarm, const Time& i_nowTime) { const bool moved = io_alarm.GoToRepeatAt(m_nowDate, i_nowTime, m_isReversedTime); return moved; } AlarmId AlarmComponent::AddAlarm(AlarmHandle&& io_alarmHandle, const Time& i_nowTime) { auto result = m_allAlarms.find(io_alarmHandle); if(result != m_allAlarms.end()) { const AlarmId existingAlarmId = result->GetAlarmId(); return existingAlarmId; } AlarmHandle candidateAlarmHandle = AlarmHandle::ReWrapAlarm(AZStd::move(io_alarmHandle)); Alarm* candidateAlarm = candidateAlarmHandle.GetAlarm(); AZ_Assert(candidateAlarm != nullptr, "New alarm cannot be empty"); const bool hasRepeats = DiscardPastAlarmRepeats(*candidateAlarm, i_nowTime); if(!hasRepeats) { return 0; } AlarmId nTries = 0; const AlarmId maxTries = AZStd::numeric_limits<AlarmId>::max(); do { auto [ newAlarmHandle, inserted ] = m_allAlarms.insert(AZStd::move(candidateAlarmHandle)); if(!inserted) { candidateAlarmHandle = AlarmHandle::ReWrapAlarm(AZStd::move(candidateAlarmHandle)); ++nTries; continue; } auto newAlarmHandleAddress = &(*newAlarmHandle); m_orderedAlarms.emplace(newAlarmHandleAddress); const AlarmId newAlarmId = newAlarmHandle->GetAlarmId(); return newAlarmId; } while(nTries < maxTries); AZ_Assert(false, "Unable to find a free ID to insert the new alarm"); return 0; } void AlarmComponent::AddAlarmsFromConfig(const AZStd::vector<AlarmConfig>& i_alarmConfigs) { const Time emptyTime; for(const auto& alarmConfig : i_alarmConfigs) { AZStd::unique_ptr<DateRecurrenceRule> dateRule = alarmConfig.m_dateRule.CalculateRecurrenceRule(); AZStd::unique_ptr<TimeRecurrenceRule> timeRule = alarmConfig.m_timeRule.CalculateRecurrenceRule(); AlarmHandle alarmHandle; switch(alarmConfig.m_action) { case AlarmConfig::AlarmActionType::NOTIFY_REQUESTER: { alarmHandle = Alarm::CreateInstance(AZStd::move(dateRule), AZStd::move(timeRule), alarmConfig.m_actionRequesterId); } break; default: { AZ_Assert(false, "Unsupported action: %d", alarmConfig.m_action); return; } } if(alarmConfig.m_isSilent) { Alarm* alarm = alarmHandle.GetAlarm(); alarm->Silence(true); } AddAlarm(AZStd::move(alarmHandle), emptyTime); } } bool AlarmComponent::CalculateTimeDirection(float i_timeSpeed) { if(AZ::IsClose(i_timeSpeed, 0.0f, AZ::Constants::FloatEpsilon)) { return false; } bool oldReversedTime = m_isReversedTime; m_isReversedTime = (i_timeSpeed < 0.f); return (m_isReversedTime != oldReversedTime); } void AlarmComponent::ProcessAlarms(const Time& i_nowTime) { while(!m_orderedAlarms.empty()) { AlarmHandle* const alarmHandle = m_orderedAlarms.top(); Alarm* alarm = alarmHandle->GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); if(!alarm->IsGoneOff(m_nowDate, i_nowTime, m_isReversedTime)) { if(!m_hasDate) { if(m_lastHours > i_nowTime.GetHours()) { for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->ClearExtension(); } } m_lastHours = i_nowTime.GetHours(); } return; } bool hasRepeat; if(!alarm->IsCanceled()) { if(!alarm->IsSilent()) { if(const AZ::EntityId* requesterId = alarm->GetActionIfType<AZ::EntityId>()) { EBUS_EVENT_ID(*requesterId, AlarmNotificationBus, OnAlarmBell, alarm->GetDate(), alarm->GetTime()); } else if(const AlarmCallback* callback = alarm->GetActionIfType<AlarmCallback>()) { (*callback)(alarm->GetDate(), alarm->GetTime()); } else { AZ_Assert(false, "Unexpected action type: %d", alarm->GetActionType()); return; } } hasRepeat = alarm->NextRepeat(m_isReversedTime); } else { hasRepeat = false; } m_orderedAlarms.pop(); if(hasRepeat) { m_orderedAlarms.emplace(alarmHandle); } else { auto result = m_allAlarms.find(*alarmHandle); if(result != m_allAlarms.end()) { m_allAlarms.erase(result); } } } } void AlarmComponent::ResetAlarms(const Time& i_nowTime) { if(!m_orderedAlarms.empty()) { m_orderedAlarms = AlarmQueue { m_alarmPrioritizer }; } for(auto& alarmHandle : m_allAlarms) { Alarm* alarm = alarmHandle.GetAlarm(); AZ_Assert(alarm != nullptr, "An empty handler cannot be stored in the alarm queue"); alarm->Reset(); const bool hasRepeats = DiscardPastAlarmRepeats(*alarm, i_nowTime); if(!hasRepeats) { continue; } m_orderedAlarms.emplace(&alarmHandle); } } void AlarmComponent::SynchronizeWithDateAndTimeComponents() { Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); if(!nowTime.IsValid()) { AZ_Assert(false, "A running TimeComponent instance is required to process alarms, but none was found"); return; } float timeSpeed; EBUS_EVENT_RESULT(timeSpeed, TimeRequestBus, GetTimeSpeed); CalculateTimeDirection(timeSpeed); Date nowDate; EBUS_EVENT_RESULT(nowDate, DateRequestBus, GetCurrentDate); m_hasDate = nowDate.IsValid(); if(!m_hasDate) { AZ_Warning("AlarmLevelComponent", false, "Unable to find a DateComponent instance to synchronize with. Alarms will only be checked against time"); } m_nowDate = nowDate; ResetAlarms(nowTime); } Time AlarmComponent::GetCurrentTime() const { Time nowTime; EBUS_EVENT_RESULT(nowTime, TimeRequestBus, GetCurrentTime); AZ_Assert(nowTime.IsValid(), "A running TimeComponent instance is required to add a new alarm, but none was found"); return nowTime; } // --- bool AlarmComponent::AlarmComparator::operator()(const AlarmHandle& i_lhs, const AlarmHandle& i_rhs) const { return (i_lhs.CompareTo(i_rhs) == AlarmComparison::LESS_THAN); } AlarmComponent::AlarmPrioritizer::AlarmPrioritizer(bool i_reverse) : m_isReversedTime { i_reverse } {} bool AlarmComponent::AlarmPrioritizer::operator()(const AlarmHandle* i_lhs, const AlarmHandle* i_rhs) const { return (i_lhs->CompareTo(*i_rhs) == ((m_isReversedTime) ? AlarmComparison::LESS_THAN : AlarmComparison::GREATER_THAN)); }
26.542254
215
0.749005
loherangrin
6e4db13dd48163951056ee2a1dd16077f5c80020
9,380
cpp
C++
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
DlgSongProperties.cpp
addam/SkauTan
a46b60e91741da343a50a63948d3a19d961550d0
[ "Unlicense" ]
null
null
null
#include "DlgSongProperties.h" #include <assert.h> #include <QDebug> #include <QMessageBox> #include "ui_DlgSongProperties.h" #include "Database.h" #include "Settings.h" #include "Utils.h" DlgSongProperties::DlgSongProperties( Database & a_DB, SongPtr a_Song, QWidget * a_Parent ) : Super(a_Parent), m_UI(new Ui::DlgSongProperties), m_DB(a_DB), m_Song(a_Song), m_Duplicates(a_Song->duplicates()) { // Initialize the ChangeSets: m_TagManual = m_Song->tagManual(); m_Notes = m_Song->notes(); for (const auto & song: m_Duplicates) { m_TagID3Changes[song] = song->tagId3(); } // Initialize the UI: m_UI->setupUi(this); Settings::loadWindowPos("DlgSongProperties", *this); auto genres = Song::recognizedGenres(); genres.insert(0, ""); m_UI->cbManualGenre->addItems(genres); m_UI->cbManualGenre->setMaxVisibleItems(genres.count()); m_UI->lwDuplicates->addActions({ m_UI->actRemoveFromLibrary, m_UI->actDeleteFromDisk, }); // Connect the signals: connect(m_UI->btnCancel, &QPushButton::clicked, this, &DlgSongProperties::reject); connect(m_UI->btnOK, &QPushButton::clicked, this, &DlgSongProperties::applyAndClose); connect(m_UI->leManualAuthor, &QLineEdit::textEdited, this, &DlgSongProperties::authorTextEdited); connect(m_UI->leManualTitle, &QLineEdit::textEdited, this, &DlgSongProperties::titleTextEdited); connect(m_UI->cbManualGenre, &QComboBox::currentTextChanged, this, &DlgSongProperties::genreSelected); connect(m_UI->leManualMeasuresPerMinute, &QLineEdit::textEdited, this, &DlgSongProperties::measuresPerMinuteTextEdited); connect(m_UI->pteNotes, &QPlainTextEdit::textChanged, this, &DlgSongProperties::notesChanged); connect(m_UI->lwDuplicates, &QListWidget::currentRowChanged, this, &DlgSongProperties::switchDuplicate); connect(m_UI->actRemoveFromLibrary, &QAction::triggered, this, &DlgSongProperties::removeFromLibrary); connect(m_UI->actDeleteFromDisk, &QAction::triggered, this, &DlgSongProperties::deleteFromDisk); // Set the read-only edit boxes' palette to greyed-out: auto p = palette(); p.setColor(QPalette::Active, QPalette::Base, p.color(QPalette::Disabled, QPalette::Base)); p.setColor(QPalette::Inactive, QPalette::Base, p.color(QPalette::Disabled, QPalette::Base)); m_UI->leHash->setPalette(p); m_UI->leLength->setPalette(p); m_UI->leId3Author->setPalette(p); m_UI->leId3Title->setPalette(p); m_UI->leId3Genre->setPalette(p); m_UI->leId3MeasuresPerMinute->setPalette(p); m_UI->leFilenameAuthor->setPalette(p); m_UI->leFilenameTitle->setPalette(p); m_UI->leFilenameGenre->setPalette(p); m_UI->leFilenameMeasuresPerMinute->setPalette(p); // Fill in the data: m_IsInternalChange = true; m_UI->leHash->setText(Utils::toHex(a_Song->hash())); auto length = m_Song->length(); if (length.isValid()) { auto numSeconds = static_cast<int>(length.toDouble() + 0.5); m_UI->leLength->setText(tr("%1:%2 (%n seconds)", "SongLength", numSeconds) .arg(QString::number(numSeconds / 60)) .arg(QString::number(numSeconds % 60), 2, '0') ); } m_UI->leManualAuthor->setText(m_TagManual.m_Author.valueOrDefault()); m_UI->leManualTitle->setText(m_TagManual.m_Title.valueOrDefault()); m_UI->cbManualGenre->setCurrentText(m_TagManual.m_Genre.valueOrDefault()); if (m_TagManual.m_MeasuresPerMinute.isPresent()) { m_UI->leManualMeasuresPerMinute->setText(QLocale::system().toString(m_TagManual.m_MeasuresPerMinute.value())); } else { m_UI->leManualMeasuresPerMinute->clear(); } m_UI->pteNotes->setPlainText(m_Notes.valueOrDefault()); m_IsInternalChange = false; fillDuplicates(); selectSong(*m_Song); } DlgSongProperties::~DlgSongProperties() { Settings::saveWindowPos("DlgSongProperties", *this); } void DlgSongProperties::fillDuplicates() { int row = 0; for (const auto & song: m_Duplicates) { auto item = new QListWidgetItem(song->fileName()); item->setData(Qt::UserRole, reinterpret_cast<qulonglong>(song)); m_UI->lwDuplicates->addItem(item); row += 1; } } void DlgSongProperties::selectSong(const Song & a_Song) { // Select the song in tblDuplicates: m_IsInternalChange = true; m_Song = songPtrFromRef(a_Song); assert(m_Song != nullptr); auto numRows = m_UI->lwDuplicates->count(); for (int row = 0; row < numRows; ++row) { auto itemSong = reinterpret_cast<const Song *>(m_UI->lwDuplicates->item(row)->data(Qt::UserRole).toULongLong()); if (itemSong == &a_Song) { m_UI->lwDuplicates->setCurrentRow(row); break; } } const auto loc = QLocale::system(); m_UI->leId3Author->setText(a_Song.tagId3().m_Author.valueOrDefault()); m_UI->leId3Title->setText(a_Song.tagId3().m_Title.valueOrDefault()); m_UI->leId3Genre->setText(a_Song.tagId3().m_Genre.valueOrDefault()); if (a_Song.tagId3().m_MeasuresPerMinute.isPresent()) { m_UI->leId3MeasuresPerMinute->setText(loc.toString(a_Song.tagId3().m_MeasuresPerMinute.value())); } else { m_UI->leId3MeasuresPerMinute->clear(); } m_UI->leFilenameAuthor->setText(a_Song.tagFileName().m_Author.valueOrDefault()); m_UI->leFilenameTitle->setText(a_Song.tagFileName().m_Title.valueOrDefault()); m_UI->leFilenameGenre->setText(a_Song.tagFileName().m_Genre.valueOrDefault()); if (a_Song.tagFileName().m_MeasuresPerMinute.isPresent()) { m_UI->leFilenameMeasuresPerMinute->setText(loc.toString(a_Song.tagFileName().m_MeasuresPerMinute.value())); } else { m_UI->leFilenameMeasuresPerMinute->clear(); } m_IsInternalChange = false; } SongPtr DlgSongProperties::songPtrFromRef(const Song & a_Song) { for (const auto & song: m_Duplicates) { if (song == &a_Song) { return song->shared_from_this(); } } return nullptr; } void DlgSongProperties::applyAndClose() { m_Song->sharedData()->m_TagManual = m_TagManual; m_Song->sharedData()->m_Notes = m_Notes; m_DB.saveSongSharedData(m_Song->sharedData()); for (const auto & song: m_Duplicates) { const auto & cs = m_TagID3Changes[song]; // TODO: Apply the tag changes (#128) Q_UNUSED(cs); // m_DB.saveSong(song); } accept(); } void DlgSongProperties::authorTextEdited(const QString & a_NewText) { if (!m_IsInternalChange) { m_TagManual.m_Author = a_NewText; } } void DlgSongProperties::titleTextEdited(const QString & a_NewText) { if (!m_IsInternalChange) { m_TagManual.m_Title = a_NewText; } } void DlgSongProperties::genreSelected(const QString & a_NewGenre) { if (!m_IsInternalChange) { m_TagManual.m_Genre = a_NewGenre; } } void DlgSongProperties::measuresPerMinuteTextEdited(const QString & a_NewText) { if (m_IsInternalChange) { return; } if (a_NewText.isEmpty()) { m_UI->leManualMeasuresPerMinute->setStyleSheet(""); m_TagManual.m_MeasuresPerMinute.reset(); return; } bool isOK; auto mpm = QLocale::system().toDouble(a_NewText, &isOK); if (isOK) { m_UI->leManualMeasuresPerMinute->setStyleSheet(""); m_TagManual.m_MeasuresPerMinute = mpm; } else { m_UI->leManualMeasuresPerMinute->setStyleSheet("background-color:#fcc"); } } void DlgSongProperties::notesChanged() { m_Notes = m_UI->pteNotes->toPlainText(); } void DlgSongProperties::switchDuplicate(int a_Row) { if ((a_Row < 0) || (a_Row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << a_Row << " out of " << m_Duplicates.size(); return; } auto song = m_Duplicates[static_cast<size_t>(a_Row)]; selectSong(*song); } void DlgSongProperties::removeFromLibrary() { auto row = m_UI->lwDuplicates->currentRow(); if ((row < 0) || (row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << row; return; } auto song = m_Duplicates[static_cast<size_t>(row)]->shared_from_this(); assert(song != nullptr); // Ask for confirmation: if (QMessageBox::question( this, tr("SkauTan: Remove songs?"), tr( "Are you sure you want to remove the song %1 from the library? The song file will stay " "on the disk, but all properties set in the library will be lost.\n\n" "This operation cannot be undone!" ).arg(song->fileName()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::No) { return; } // Remove from the DB: m_DB.removeSong(*song, false); m_Duplicates.erase(m_Duplicates.begin() + row); delete m_UI->lwDuplicates->takeItem(row); } void DlgSongProperties::deleteFromDisk() { auto row = m_UI->lwDuplicates->currentRow(); if ((row < 0) || (row >= static_cast<int>(m_Duplicates.size()))) { qWarning() << "Invalid row: " << row; return; } auto song = m_Duplicates[static_cast<size_t>(row)]->shared_from_this(); assert(song != nullptr); // Ask for confirmation: if (QMessageBox::question( this, tr("SkauTan: Remove songs?"), tr( "Are you sure you want to delete the file %1 from the disk? " "The file will be deleted and all its properties set in the library will be lost.\n\n" "This operation cannot be undone!" ).arg(song->fileName()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape ) == QMessageBox::No) { return; } // Delete from the disk: m_DB.removeSong(*song, true); m_Duplicates.erase(m_Duplicates.begin() + row); delete m_UI->lwDuplicates->takeItem(row); }
25.48913
130
0.707143
addam
6e54992eea4715de53e651cc99cc17caeae4c0f1
3,010
hpp
C++
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_BP_TslBaseLobbySceneTravel_FadeInOut_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.UserConstructionScript struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_UserConstructionScript_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeInOut__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeInOut__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeInOut__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeInOut__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeIn__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeIn__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeIn__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeIn__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeOut__FinishedFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeOut__FinishedFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.FadeOut__UpdateFunc struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_FadeOut__UpdateFunc_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.OnStartTravel struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_OnStartTravel_Params { }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ReceiveEndPlay struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ReceiveEndPlay_Params { TEnumAsByte<EEndPlayReason> EndPlayReason; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ReceiveTick struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ReceiveTick_Params { float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function BP_TslBaseLobbySceneTravel_FadeInOut.BP_TslBaseLobbySceneTravel_FadeInOut_C.ExecuteUbergraph_BP_TslBaseLobbySceneTravel_FadeInOut struct ABP_TslBaseLobbySceneTravel_FadeInOut_C_ExecuteUbergraph_BP_TslBaseLobbySceneTravel_FadeInOut_Params { int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
37.625
152
0.772757
realrespecter
6e5d0a1f79c6f9d2b44e14eea33ddc2f6dfa59cd
258
hpp
C++
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/OCGL_Buffer.hpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
#pragma once #include <NTL.hpp> #include <glad/glad.h> class OCGL_Buffer { public: OCGL_Buffer(size_t size); OCGL_Buffer(OCGL_Buffer const &deviceBuffer); OCGL_Buffer &operator=(OCGL_Buffer const &deviceBuffer); GLuint vbo; cl::Memory mem; };
17.2
60
0.728682
Jino42
6e6321da04804ffe3b088f4c0bec09eff53a567b
8,430
cpp
C++
src/sdk/hl2_csgo/game/missionchooser/vgui/RoomTemplateListPanel.cpp
newcommerdontblame/ionlib
47ca829009e1529f62b2134aa6c0df8673864cf3
[ "MIT" ]
51
2016-03-18T01:48:07.000Z
2022-03-21T20:02:02.000Z
src/game/missionchooser/vgui/RoomTemplateListPanel.cpp
senny970/AlienSwarm
c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84
[ "Unlicense" ]
null
null
null
src/game/missionchooser/vgui/RoomTemplateListPanel.cpp
senny970/AlienSwarm
c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84
[ "Unlicense" ]
26
2016-03-17T21:20:37.000Z
2022-03-24T10:21:30.000Z
#include <vgui/IVGui.h> #include <vgui/IInput.h> #include "vgui_controls/Controls.h" #include <vgui/IScheme.h> #include <vgui_controls/ImagePanel.h> #include <vgui_controls/Button.h> #include <KeyValues.h> #include "TileGenDialog.h" #include "RoomTemplateListPanel.h" #include "RoomTemplatePanel.h" #include "TileSource/RoomTemplate.h" #include "TileSource/LevelTheme.h" #include "vgui/missionchooser_tgaimagepanel.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; CRoomTemplateListPanel::CRoomTemplateListPanel( Panel *parent, const char *name ) : BaseClass( parent, name ), m_RoomTemplateFolders( 0, 20 ) { KeyValues *pMessageKV; m_FilterText[0] = '\0'; m_pRefreshList = new Button( this, "RefreshListButton", "Refresh List", this, "RefreshList" ); pMessageKV = new KeyValues( "RefreshList" ); m_pRefreshList->SetCommand( pMessageKV ); m_pExpandAll = new Button( this, "ExpandAllButton", "Expand All", this, "ExpandAllFolders" ); pMessageKV = new KeyValues( "ExpandAllFolders" ); m_pExpandAll->SetCommand( pMessageKV ); m_pCollapseAll = new Button( this, "CollapseAllButton", "Collapse All", this, "CollapseAllFolders" ); pMessageKV = new KeyValues( "CollapseAllFolders" ); m_pCollapseAll->SetCommand( pMessageKV ); } CRoomTemplateListPanel::~CRoomTemplateListPanel( void ) { } void CRoomTemplateListPanel::PerformLayout() { // Set width to match parent panel SetWide( GetParent()->GetWide() ); int padding = 8; int cur_x = padding; int cur_y = padding; int nPanelWidth = GetWide(); int tallest_on_this_row = 0; // Place the refresh and expand/collapse buttons int nButtonWidth = nPanelWidth - 2 * padding; m_pRefreshList->SetBounds( padding, cur_y, nButtonWidth, 24 ); cur_y += 24 + padding; nButtonWidth = ( nPanelWidth - 3 * padding ) / 2; nButtonWidth = MAX( nButtonWidth, 40 ); m_pExpandAll->SetBounds( padding, cur_y, nButtonWidth, 24 ); m_pCollapseAll->SetBounds( 2 * padding + nButtonWidth, cur_y, nButtonWidth, 24 ); cur_y += 24 + padding; // Place buttons and images for each folder of room templates for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].SetButtonText(); m_RoomTemplateFolders[i].m_pFolderButton->SetBounds(padding, cur_y, GetWide() - padding * 2, 24); cur_y += 24; // Add every room template in this category for ( int j = 0; j < m_Thumbnails.Count(); ++ j ) { if ( Q_stricmp( m_Thumbnails[j]->m_pRoomTemplate->GetFolderName(), m_RoomTemplateFolders[i].m_FolderName ) != 0 ) continue; if ( m_RoomTemplateFolders[i].m_bExpanded && FilterTemplate( m_Thumbnails[j]->m_pRoomTemplate ) ) { m_Thumbnails[j]->SetVisible( true ); // make sure the template has sized itself m_Thumbnails[j]->InvalidateLayout( true ); int tw = m_Thumbnails[j]->GetWide(); int tt = m_Thumbnails[j]->GetTall(); // if the panel is too wide to fit, then move down a row if (cur_x + tw > nPanelWidth) { cur_x = padding; cur_y += tallest_on_this_row + padding; tallest_on_this_row = 0; } m_Thumbnails[j]->SetPos(cur_x, cur_y); if (tt > tallest_on_this_row) tallest_on_this_row = tt; cur_x += tw + padding; } else { m_Thumbnails[j]->SetVisible( false ); } } cur_y += tallest_on_this_row + padding; tallest_on_this_row = 0; cur_x = padding; } SetTall( cur_y ); } void CRoomTemplateListPanel::UpdatePanelsWithTemplate( const CRoomTemplate* pTemplate ) { int thumbs = m_Thumbnails.Count(); for (int i=0;i<thumbs;i++) { CRoomTemplatePanel* pPanel = m_Thumbnails[i]; if (!pPanel) continue; if (pPanel->m_pRoomTemplate == pTemplate) pPanel->UpdateImages(); } } void CRoomTemplateListPanel::UpdateRoomList() { // clear out the list for ( int i = 0; i < m_Thumbnails.Count(); ++ i ) { m_Thumbnails[i]->MarkForDeletion(); } m_Thumbnails.RemoveAll(); // Try to re-use folder buttons and preserve their state when possible. // Mark all folder buttons invisible to begin with. If they are needed, they will be // made visible again; otherwise, we can cull them. for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_pFolderButton->SetVisible( false ); } // Add every room template for the currently selected theme CLevelTheme *pCurrentTheme = CLevelTheme::s_pCurrentTheme; if ( pCurrentTheme == NULL ) return; for (int i = 0; i < pCurrentTheme->m_RoomTemplates.Count(); ++ i ) { CRoomTemplatePanel *pPanel = new CRoomTemplatePanel( this, "RoomTemplatePanel" ); pPanel->m_bRoomTemplateBrowserMode = true; pPanel->SetRoomTemplate( pCurrentTheme->m_RoomTemplates[i] ); m_Thumbnails.AddToTail( pPanel ); AddFolder( pCurrentTheme->m_RoomTemplates[i]->GetFolderName() ); } // Remove unused folder buttons for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { if ( !m_RoomTemplateFolders[i].m_pFolderButton->IsVisible() ) { m_RoomTemplateFolders[i].m_pFolderButton->MarkForDeletion(); m_RoomTemplateFolders.FastRemove( i ); // go back 1 since we just deleted an entry -- i; } } // Sort alphabetically m_RoomTemplateFolders.Sort( CompareFolders ); InvalidateLayout(); } void CRoomTemplateListPanel::OnRefreshList() { CLevelTheme *pCurrentTheme = CLevelTheme::s_pCurrentTheme; if ( pCurrentTheme == NULL ) return; CMissionChooserTGAImagePanel::ClearImageCache(); pCurrentTheme->LoadRoomTemplates(); UpdateRoomList(); } void CRoomTemplateListPanel::OnExpandAll() { for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_bExpanded = true; } InvalidateLayout(); } void CRoomTemplateListPanel::OnCollapseAll() { for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { m_RoomTemplateFolders[i].m_bExpanded = false; } InvalidateLayout(); } void CRoomTemplateListPanel::OnToggleFolder( KeyValues *pKV ) { const char *pFolderName = pKV->GetString( "folder", NULL ); Assert( pFolderName != NULL); for ( int i = 0; i < m_RoomTemplateFolders.Count(); ++ i ) { if ( Q_stricmp( pFolderName, m_RoomTemplateFolders[i].m_FolderName ) == 0 ) { m_RoomTemplateFolders[i].m_bExpanded = !m_RoomTemplateFolders[i].m_bExpanded; InvalidateLayout(); return; } } } void CRoomTemplateListPanel::SetFilterText( const char *pText ) { Q_strncpy( m_FilterText, pText, m_nFilterTextLength ); } void CRoomTemplateListPanel::AddFolder( const char *pFolderName ) { int nNumFolders = m_RoomTemplateFolders.Count(); for ( int i = 0; i < nNumFolders; ++ i ) { if ( Q_stricmp( pFolderName, m_RoomTemplateFolders[i].m_FolderName ) == 0 ) { // Mark this folder as being used m_RoomTemplateFolders[i].m_pFolderButton->SetVisible( true ); return; } } // New folder, create a new entry m_RoomTemplateFolders.AddToTail(); Q_strncpy( m_RoomTemplateFolders[nNumFolders].m_FolderName, pFolderName, MAX_PATH ); m_RoomTemplateFolders[nNumFolders].m_bExpanded = true; m_RoomTemplateFolders[nNumFolders].m_pFolderButton = new Button( this, "FolderButton", "", this, "ToggleFolder" ); KeyValues *pMessageKV = new KeyValues( "ToggleFolder" ); KeyValues *pIndexKV = new KeyValues( "folder" ); pIndexKV->SetString( NULL, m_RoomTemplateFolders[nNumFolders].m_FolderName ); pMessageKV->AddSubKey( pIndexKV ); m_RoomTemplateFolders[nNumFolders].m_pFolderButton->SetCommand( pMessageKV ); } bool CRoomTemplateListPanel::FilterTemplate( const CRoomTemplate *pTemplate ) { bool bInvert = false; const char *pFilterText = m_FilterText; // If the user types in a "!" as the first character, invert the search results. if ( pFilterText[0] == '!' ) { bInvert = true; ++ pFilterText; } if ( pFilterText[0] == '\0' ) { return true; } else { if ( Q_stristr( pTemplate->GetDescription(), pFilterText ) != NULL ) { return !bInvert; } if ( Q_stristr( pTemplate->GetFullName(), pFilterText ) != NULL ) { return !bInvert; } int nNumTags = pTemplate->GetNumTags(); for ( int i = 0; i < nNumTags; ++ i ) { if ( Q_stristr( pTemplate->GetTag( i ), pFilterText ) != NULL ) { return !bInvert; } } } return bInvert; } void CRoomTemplateListPanel::RoomTemplateFolder_t::SetButtonText() { char buttonLabel[MAX_PATH + 5]; Q_snprintf( buttonLabel, MAX_PATH + 5, "%s %s", m_bExpanded ? "-" : "+", m_FolderName ); m_pFolderButton->SetText( buttonLabel ); }
28.19398
116
0.707355
newcommerdontblame
6e65502e96a12437e12aad53ae1f8063e28098ee
2,529
cpp
C++
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
1
2022-03-26T07:05:21.000Z
2022-03-26T07:05:21.000Z
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
null
null
null
011/011.cpp
joeymich/Project-Euler
a061f6ecc2afa9f95f3727380443dfc6e8d43db0
[ "MIT" ]
null
null
null
// Problem 11 -- Largest product in a grid /* 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 */ #include <iostream> #include <vector> using namespace std; int main() { vector<vector<int>> grid(20, vector<int>(20, 0)); for (unsigned int i = 0; i < 20; i++) for (unsigned int j = 0; j < 20; j++) cin >> grid.at(i).at(j); unsigned long long solution = 0; for (unsigned int i = 0; i < grid.size(); i++) { for (unsigned int j = 0; j < grid[i].size() - 3; j++) { unsigned long long temp1 = 1; // horizontal unsigned long long temp2 = 1; // vertical unsigned long long temp3 = 1; // up diagonal unsigned long long temp4 = 1; // down diagonal for (unsigned int k = 0; k < 4; k++) { temp1 *= grid[i][j + k]; temp2 *= grid[j + k][i]; if (i > 2) temp3 *= grid[i - k][j + k]; if (i < grid.size() - 3) temp4 *= grid[i + k][j + k]; } if (temp1 > solution) solution = temp1; if (temp2 > solution) solution = temp2; if (temp3 > solution) solution = temp3; if (temp4 > solution) solution = temp4; } } cout << solution << "\n"; return 0; }
40.142857
63
0.550415
joeymich
6e6747cd12f03d84ef2675e5a7b0bdb74173bc1b
1,145
hpp
C++
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
35
2018-01-07T02:34:38.000Z
2022-02-09T05:19:03.000Z
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
111
2017-09-20T09:12:36.000Z
2020-12-27T12:52:03.000Z
gearoenix/vulkan/texture/gx-vk-txt-cube.hpp
Hossein-Noroozpour/gearoenix
c8fa8b8946c03c013dad568d6d7a97d81097c051
[ "BSD-Source-Code" ]
5
2020-02-11T11:17:37.000Z
2021-01-08T17:55:43.000Z
#ifndef GEAROENIX_VULKAN_TEXTURE_CUBE_HPP #define GEAROENIX_VULKAN_TEXTURE_CUBE_HPP #include "../../core/gx-cr-build-configuration.hpp" #ifdef GX_USE_VULKAN #include "../../core/sync/gx-cr-sync-end-caller.hpp" #include "../../render/texture/gx-rnd-txt-texture-cube.hpp" #include "../../render/texture/gx-rnd-txt-texture-info.hpp" namespace gearoenix::vulkan::engine { class Engine; } namespace gearoenix::vulkan::image { class View; } namespace gearoenix::vulkan::texture { class TextureCube final : public render::texture::TextureCube { GX_GET_REFC_PRV(std::shared_ptr<image::View>, view) public: TextureCube( core::Id id, std::string name, engine::Engine* engine, std::vector<std::vector<std::vector<std::uint8_t>>> data, const render::texture::TextureInfo& info, std::size_t aspect, const core::sync::EndCaller<core::sync::EndCallerIgnore>& call) noexcept; ~TextureCube() noexcept final; void write_gx3d( const std::shared_ptr<system::stream::Stream>& s, const core::sync::EndCaller<core::sync::EndCallerIgnore>& c) noexcept final; }; } #endif #endif
30.945946
84
0.697817
Hossein-Noroozpour
6e67e9b6ff26bb8d951fb88800c8960d5a0cdfd5
1,019
cpp
C++
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
8
2018-10-17T00:36:46.000Z
2020-11-18T05:34:28.000Z
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
null
null
null
bp/src/OffscreenFramebuffer.cpp
larso0/bp
0aa13c6d78f6e6a1097d9231c1b9fc47ae74a9fe
[ "MIT" ]
1
2022-01-06T04:28:18.000Z
2022-01-06T04:28:18.000Z
#include <bp/OffscreenFramebuffer.h> #include <bp/RenderPass.h> namespace bp { void OffscreenFramebuffer::init(RenderPass& renderPass, uint32_t width, uint32_t height, const AttachmentSlot& colorAttachmentSlot, const AttachmentSlot& depthAttachmentSlot) { Device& device = renderPass.getDevice(); colorAttachment.init(device, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, width, height); depthAttachment.init(device, VK_FORMAT_D16_UNORM, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, width, height); depthAttachment.setClearValue({1.f, 0.f}); setAttachment(colorAttachmentSlot, colorAttachment); setAttachment(depthAttachmentSlot, depthAttachment); Framebuffer::init(renderPass, width, height); } void OffscreenFramebuffer::resize(uint32_t width, uint32_t height) { colorAttachment.resize(width, height); depthAttachment.resize(width, height); Framebuffer::resize(width, height); } }
30.878788
91
0.784102
larso0
6e6a63640b448ebb8e7891e60e2c4139077bfed4
8,080
hpp
C++
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
src/dag/dag.hpp
kostdima/taraxa
61e9a50a60049c3f989efaf6970cd99a74896767
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include <bitset> #include <boost/function.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/labeled_graph.hpp> #include <boost/graph/properties.hpp> #include <boost/property_map/property_map.hpp> #include <boost/thread.hpp> #include <chrono> #include <condition_variable> #include <iostream> #include <iterator> #include <list> #include <mutex> #include <queue> #include <string> #include "common/types.hpp" #include "consensus/pbft_chain.hpp" #include "dag_block.hpp" #include "storage/db_storage.hpp" #include "transaction_manager/transaction_manager.hpp" #include "util/util.hpp" namespace taraxa { /** * Thread safe. Labelled graph. */ class DagManager; class Dag { public: // properties using vertex_hash = std::string; using vertex_property_t = boost::property<boost::vertex_index_t, std::string, boost::property<boost::vertex_index1_t, uint64_t>>; using edge_property_t = boost::property<boost::edge_index_t, uint64_t>; // graph def using adj_list_t = boost::adjacency_list<boost::setS, boost::hash_setS, boost::directedS, vertex_property_t, edge_property_t>; using graph_t = boost::labeled_graph<adj_list_t, std::string, boost::hash_mapS>; using vertex_t = boost::graph_traits<graph_t>::vertex_descriptor; using edge_t = boost::graph_traits<graph_t>::edge_descriptor; using vertex_iter_t = boost::graph_traits<graph_t>::vertex_iterator; using edge_iter_t = boost::graph_traits<graph_t>::edge_iterator; using vertex_adj_iter_t = boost::graph_traits<graph_t>::adjacency_iterator; // property_map using vertex_index_map_const_t = boost::property_map<graph_t, boost::vertex_index_t>::const_type; using vertex_index_map_t = boost::property_map<graph_t, boost::vertex_index_t>::type; using vertex_period_map_const_t = boost::property_map<graph_t, boost::vertex_index1_t>::const_type; using vertex_period_map_t = boost::property_map<graph_t, boost::vertex_index1_t>::type; using edge_index_map_const_t = boost::property_map<graph_t, boost::edge_index_t>::const_type; using edge_index_map_t = boost::property_map<graph_t, boost::edge_index_t>::type; friend DagManager; explicit Dag(std::string const &genesis, addr_t node_addr); virtual ~Dag() = default; uint64_t getNumVertices() const; uint64_t getNumEdges() const; bool hasVertex(vertex_hash const &v) const; bool addVEEs(vertex_hash const &new_vertex, vertex_hash const &pivot, std::vector<vertex_hash> const &tips); void getLeaves(std::vector<vertex_hash> &tips) const; void drawGraph(vertex_hash filename) const; bool computeOrder(vertex_hash const &anchor, std::vector<vertex_hash> &ordered_period_vertices, std::map<uint64_t, std::vector<std::string>> const &non_finalized_blks); void clear(); protected: // Note: private functions does not lock // edge API edge_t addEdge(std::string const &v1, std::string const &v2); edge_t addEdge(vertex_t v1, vertex_t v2); // traverser API bool reachable(vertex_t const &from, vertex_t const &to) const; void collectLeafVertices(std::vector<vertex_t> &leaves) const; graph_t graph_; vertex_t genesis_; // root node protected: LOG_OBJECTS_DEFINE }; /** * PivotTree is a special DAG, every vertex only has one out-edge, * therefore, there is no convergent tree */ class PivotTree : public Dag { public: friend DagManager; explicit PivotTree(std::string const &genesis, addr_t node_addr) : Dag(genesis, node_addr){}; virtual ~PivotTree() = default; using vertex_t = Dag::vertex_t; using vertex_adj_iter_t = Dag::vertex_adj_iter_t; using vertex_index_map_const_t = Dag::vertex_index_map_const_t; void getGhostPath(vertex_hash const &vertex, std::vector<vertex_hash> &pivot_chain) const; }; class DagBuffer; class FullNode; class DagManager : public std::enable_shared_from_this<DagManager> { public: using uLock = boost::unique_lock<boost::shared_mutex>; using sharedLock = boost::shared_lock<boost::shared_mutex>; explicit DagManager(std::string const &genesis, addr_t node_addr, std::shared_ptr<TransactionManager> trx_mgr, std::shared_ptr<PbftChain> pbft_chain, std::shared_ptr<DbStorage> db); virtual ~DagManager() = default; std::shared_ptr<DagManager> getShared(); void stop(); std::string const &get_genesis() { return genesis_; } bool pivotAndTipsAvailable(DagBlock const &blk); void addDagBlock(DagBlock const &blk, bool finalized = false, bool save = true); // insert to buffer if fail // return {period, block order}, for pbft-pivot-blk proposing (does not // finalize) std::pair<uint64_t, std::shared_ptr<vec_blk_t>> getDagBlockOrder(blk_hash_t const &anchor); // receive pbft-povit-blk, update periods and finalized, return size of // ordered blocks uint setDagBlockOrder(blk_hash_t const &anchor, uint64_t period, vec_blk_t const &dag_order, const taraxa::DbStorage::BatchPtr &write_batch); bool getLatestPivotAndTips(std::string &pivot, std::vector<std::string> &tips) const; void collectTotalLeaves(std::vector<std::string> &leaves) const; void getGhostPath(std::string const &source, std::vector<std::string> &ghost) const; void getGhostPath(std::vector<std::string> &ghost) const; // get ghost path from last anchor // ----- Total graph void drawTotalGraph(std::string const &str) const; // ----- Pivot graph // can return self as pivot chain void drawPivotGraph(std::string const &str) const; void drawGraph(std::string const &dotfile) const; std::pair<uint64_t, uint64_t> getNumVerticesInDag() const; std::pair<uint64_t, uint64_t> getNumEdgesInDag() const; level_t getMaxLevel() const { return max_level_; } // DAG anchors uint64_t getLatestPeriod() const { sharedLock lock(mutex_); return period_; } std::pair<std::string, std::string> getAnchors() const { sharedLock lock(mutex_); return std::make_pair(old_anchor_, anchor_); } std::map<uint64_t, std::vector<std::string>> getNonFinalizedBlocks() const; DagFrontier getDagFrontier(); private: void recoverDag(); void addToDag(std::string const &hash, std::string const &pivot, std::vector<std::string> const &tips, uint64_t level, const taraxa::DbStorage::BatchPtr &write_batch, bool finalized = false); std::pair<std::string, std::vector<std::string>> getFrontier() const; // return pivot and tips std::atomic<level_t> max_level_ = 0; mutable boost::shared_mutex mutex_; std::shared_ptr<PivotTree> pivot_tree_; // only contains pivot edges std::shared_ptr<Dag> total_dag_; // contains both pivot and tips std::shared_ptr<TransactionManager> trx_mgr_; std::shared_ptr<PbftChain> pbft_chain_; std::shared_ptr<DbStorage> db_; std::string anchor_; // anchor of the last period std::string old_anchor_; // anchor of the second to last period uint64_t period_; // last period std::string genesis_; std::map<uint64_t, std::vector<std::string>> non_finalized_blks_; std::map<uint64_t, std::vector<std::string>> finalized_blks_; DagFrontier frontier_; LOG_OBJECTS_DEFINE }; // for graphviz template <class Property1> class vertex_label_writer { public: vertex_label_writer(Property1 name) : name(name) {} template <class Vertex> void operator()(std::ostream &out, const Vertex &v) const { out << "[label=\"" << name[v].substr(0, 8) << " " << "\"]"; } private: Property1 name; }; template <class Property> class edge_label_writer { public: explicit edge_label_writer(Property weight) : weight(weight) {} template <class Edge> void operator()(std::ostream &out, const Edge &e) const { if (weight[e] == 0) { out << "[style=\"dashed\" dir=\"back\"]"; } else { out << "[dir=\"back\"]"; } } private: Property weight; }; } // namespace taraxa
35.283843
120
0.727723
kostdima
6e6af1da2aa1e2121cebb42182a44dc806e4e110
2,426
hpp
C++
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_Landscape_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Landscape.LandscapeProxy.EditorApplySpline struct ALandscapeProxy_EditorApplySpline_Params { class USplineComponent* InSplineComponent; // (Parm, ZeroConstructor, InstancedReference, IsPlainOldData) float StartWidth; // (Parm, ZeroConstructor, IsPlainOldData) float EndWidth; // (Parm, ZeroConstructor, IsPlainOldData) float StartSideFalloff; // (Parm, ZeroConstructor, IsPlainOldData) float EndSideFalloff; // (Parm, ZeroConstructor, IsPlainOldData) float StartRoll; // (Parm, ZeroConstructor, IsPlainOldData) float EndRoll; // (Parm, ZeroConstructor, IsPlainOldData) int NumSubdivisions; // (Parm, ZeroConstructor, IsPlainOldData) bool bRaiseHeights; // (Parm, ZeroConstructor, IsPlainOldData) bool bLowerHeights; // (Parm, ZeroConstructor, IsPlainOldData) class ULandscapeLayerInfoObject* PaintLayer; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function Landscape.LandscapeProxy.ChangeLODDistanceFactor struct ALandscapeProxy_ChangeLODDistanceFactor_Params { float InLODDistanceFactor; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
55.136364
172
0.40643
Milxnor
6e6bb91077029d71cde67930680eda2bdbdc66fe
4,131
cpp
C++
Kamek/src/meteor.cpp
H1dd3nM1nd/NewerSMBW
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
1
2021-06-21T04:11:04.000Z
2021-06-21T04:11:04.000Z
Kamek/src/meteor.cpp
CLF78/NSMASR-Code
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
null
null
null
Kamek/src/meteor.cpp
CLF78/NSMASR-Code
b747e89375245a1da650b186181d2b94a12387a0
[ "MIT" ]
null
null
null
#include <common.h> #include <game.h> #include <g3dhax.h> #include <sfx.h> #include "boss.h" const char* MEarcNameList [] = { "kazan_rock", NULL }; class dMeteor : public dEn_c { int onCreate(); int onDelete(); int onExecute(); int onDraw(); static dMeteor *build(); mHeapAllocator_c allocator; m3d::mdl_c bodyModel; nw4r::g3d::ResFile resFile; mEf::es2 effect; int spinSpeed; char spinDir; char isElectric; Physics MakeItRound; void updateModelMatrices(); void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther); public: void kill(); }; dMeteor *dMeteor::build() { void *buffer = AllocFromGameHeap1(sizeof(dMeteor)); return new(buffer) dMeteor; } void dMeteor::playerCollision(ActivePhysics *apThis, ActivePhysics *apOther) { DamagePlayer(this, apThis, apOther); } bool dMeteor::collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther) { this->playerCollision(apThis, apOther); return true; } void MeteorPhysicsCallback(dMeteor *self, dEn_c *other) { if (other->name == 657) { OSReport("CANNON COLLISION"); SpawnEffect("Wm_en_explosion", 0, &other->pos, &(S16Vec){0,0,0}, &(Vec){1.0, 1.0, 1.0}); SpawnEffect("Wm_en_explosion_smk", 0, &other->pos, &(S16Vec){0,0,0}, &(Vec){1.0, 1.0, 1.0}); PlaySound(other, SE_OBJ_TARU_BREAK); other->Delete(1); switch ((self->settings >> 24) & 3) { case 1: dStageActor_c::create(EN_HATENA_BALLOON, 0x100, &self->pos, 0, self->currentLayerID); break; case 2: VEC3 coinPos = {self->pos.x - 16.0f, self->pos.y, self->pos.z}; dStageActor_c::create(EN_COIN, 9, &coinPos, 0, self->currentLayerID); break; } self->kill(); } } int dMeteor::onCreate() { // Setup Model allocator.link(-1, GameHeaps[0], 0, 0x20); this->resFile.data = getResource("kazan_rock", "g3d/kazan_rock.brres"); nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("kazan_rock"); bodyModel.setup(mdl, &allocator, 0x224, 1, 0); SetupTextures_Enemy(&bodyModel, 0); allocator.unlink(); // Retrieve Scale and set it up float sca = (float)((this->settings >> 8) & 0xFF); sca = (sca/5.0) + 0.2; this->scale = (Vec){sca,sca,sca}; // Other settings this->spinDir = this->settings & 0x1; this->spinSpeed = ((this->settings >> 16) & 0xFF) * 20; this->isElectric = (this->settings >> 4) & 0x1; // Setup Physics if (isElectric) { ActivePhysics::Info elec; elec.xDistToCenter = 0.0; elec.yDistToCenter = 0.0; elec.xDistToEdge = 13.0 * sca; elec.yDistToEdge = 13.0 * sca; elec.category1 = 3; elec.category2 = 0; elec.bitfield1 = 0x4F; elec.bitfield2 = 0x200; elec.unkShort1C = 0; elec.callback = &dEn_c::collisionCallback; this->aPhysics.initWithStruct(this, &elec); this->aPhysics.addToList(); } MakeItRound.baseSetup(this, &MeteorPhysicsCallback, &MeteorPhysicsCallback, &MeteorPhysicsCallback, 1, 0); MakeItRound.x = 0.0; MakeItRound.y = 0.0; MakeItRound.diameter = 13.0 * sca; MakeItRound.isRound = 1; MakeItRound.update(); MakeItRound.addToList(); this->pos.z = (settings & 0x1000000) ? -2000.0f : 3458.0f; return true; } int dMeteor::onDelete() { return true; } int dMeteor::onExecute() { if (spinDir == 0) rot.z -= spinSpeed; else rot.z += spinSpeed; MakeItRound.update(); updateModelMatrices(); if (isElectric) { effect.spawn("Wm_en_birikyu_biri", 0, &(Vec){pos.x, pos.y, pos.z+500.0}, &rot, &(Vec){scale.x*0.8, scale.y*0.8, scale.z*0.8}); PlaySound(this, SE_EMY_BIRIKYU_SPARK); } return true; } int dMeteor::onDraw() { bodyModel.scheduleForDrawing(); bodyModel._vf1C(); return true; } void dMeteor::updateModelMatrices() { // This won't work with wrap because I'm lazy. matrix.translation(pos.x, pos.y, pos.z); matrix.applyRotationYXZ(&rot.x, &rot.y, &rot.z); bodyModel.setDrawMatrix(matrix); bodyModel.setScale(&scale); bodyModel.calcWorld(false); } void dMeteor::kill() { PlaySound(this, SE_OBJ_ROCK_LAND); SpawnEffect("Wm_ob_cmnboxsmoke", 0, &pos, &rot, &scale); SpawnEffect("Wm_ob_cmnboxgrain", 0, &pos, &rot, &scale); this->Delete(1); }
22.95
128
0.68458
H1dd3nM1nd
6e6cd33458522cbe4976a2251116feb73eb93c9e
8,752
cpp
C++
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
1
2017-03-14T12:29:06.000Z
2017-03-14T12:29:06.000Z
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
null
null
null
src/framework/factory.cpp
ancrist/apitest
cde1d337e7f0b60aa5bb943fb54219cccfa0ad06
[ "Unlicense" ]
null
null
null
#include "pch.h" #include "factory.h" #include "problems/dynamicstreaming.h" #include "problems/null.h" #include "problems/texturedquads.h" #include "problems/untexturedobjects.h" #include "solutions/dynamicstreaming/gl/buffersubdata.h" #include "solutions/dynamicstreaming/gl/mappersistent.h" #include "solutions/dynamicstreaming/gl/mapunsynchronized.h" #include "solutions/nullsoln.h" #include "solutions/untexturedobjects/gl/bindless.h" #include "solutions/untexturedobjects/gl/bindlessindirect.h" #include "solutions/untexturedobjects/gl/bufferrange.h" #include "solutions/untexturedobjects/gl/bufferstorage.h" #include "solutions/untexturedobjects/gl/dynamicbuffer.h" #include "solutions/untexturedobjects/gl/mapunsynchronized.h" #include "solutions/untexturedobjects/gl/mappersistent.h" #include "solutions/untexturedobjects/gl/drawloop.h" #include "solutions/untexturedobjects/gl/multidraw.h" #include "solutions/untexturedobjects/gl/multidrawbuffer.h" #include "solutions/untexturedobjects/gl/texcoord.h" #include "solutions/untexturedobjects/gl/uniform.h" #include "solutions/texturedquads/gl/bindless.h" #include "solutions/texturedquads/gl/bindlessmultidraw.h" #include "solutions/texturedquads/gl/naive.h" #include "solutions/texturedquads/gl/naiveuniform.h" #include "solutions/texturedquads/gl/notex.h" #include "solutions/texturedquads/gl/notexuniform.h" #include "solutions/texturedquads/gl/sparsebindlesstexturearray.h" #include "solutions/texturedquads/gl/sparsebindlesstexturearraymultidraw.h" #include "solutions/texturedquads/gl/texturearray.h" #include "solutions/texturedquads/gl/texturearrayuniform.h" #include "solutions/texturedquads/gl/texturearraymultidraw.h" // All D3D11 includes should go here. #if WITH_D3D11 # include "solutions/dynamicstreaming/d3d11/mapnooverwrite.h" # include "solutions/dynamicstreaming/d3d11/updatesubresource.h" # include "solutions/texturedquads/d3d11/naive.h" # include "solutions/untexturedobjects/d3d11/naive.h" #endif // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- ProblemFactory::ProblemFactory(bool _skipInit) { Problem* newProb = nullptr; // Null newProb = new NullProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new NullSolution()); } else { newProb->Shutdown(); SafeDelete(newProb); console::error("Unable to create the Null Problem--exiting."); } // DynamicStreaming newProb = new DynamicStreamingProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLBufferSubData()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLMapUnsynchronized()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingGLMapPersistent()); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingD3D11MapNoOverwrite()); mSolutions[mProblems.back()->GetName()].push_back(new DynamicStreamingD3D11UpdateSubresource()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } // UntexturedObjects newProb = new UntexturedObjectsProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLUniform()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLDrawLoop()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDraw(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDrawBuffer(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMultiDrawBuffer(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBindless()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBindlessIndirect()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferRange()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferStorage(true)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLBufferStorage(false)); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLDynamicBuffer()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMapUnsynchronized()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLMapPersistent()); mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsGLTexCoord()); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new UntexturedObjectsD3D11Naive()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } // Textured Quads newProb = new TexturedQuadsProblem(); if (_skipInit || newProb->Init()) { if (!_skipInit) { newProb->Shutdown(); } mProblems.push_back(newProb); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLBindless()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLBindlessMultiDraw()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNaive()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNaiveUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNoTex()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLNoTexUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArray()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArrayMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLSparseBindlessTextureArrayMultiDraw(false)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArray()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayUniform()); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayMultiDraw(true)); mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsGLTextureArrayMultiDraw(false)); #if WITH_D3D11 mSolutions[mProblems.back()->GetName()].push_back(new TexturedQuadsD3D11Naive()); #endif } else { newProb->Shutdown(); SafeDelete(newProb); } } // -------------------------------------------------------------------------------------------------------------------- ProblemFactory::~ProblemFactory() { for (auto probIt = mSolutions.begin(); probIt != mSolutions.end(); ++probIt) { for (auto solIt = probIt->second.begin(); solIt != probIt->second.end(); ++solIt) { SafeDelete(*solIt); } } for (auto probIt = mProblems.begin(); probIt != mProblems.end(); ++probIt) { SafeDelete(*probIt); } } // -------------------------------------------------------------------------------------------------------------------- std::vector<Problem*> ProblemFactory::GetProblems() { return mProblems; } // -------------------------------------------------------------------------------------------------------------------- std::vector<Solution*> ProblemFactory::GetSolutions(Problem* _problem, GfxBaseApi* _activeApi) { assert(_problem); std::vector<Solution*> tmpProblems = mSolutions[_problem->GetName()]; if (_activeApi) { EGfxApi apiType = _activeApi->GetApiType(); std::vector<Solution*> retProblems; for (auto it = tmpProblems.cbegin(); it != tmpProblems.cend(); ++it) { if ((*it)->SupportsApi(apiType)) { retProblems.push_back((*it)); } } return retProblems; } return tmpProblems; }
46.802139
121
0.650594
ancrist
6e6d5ad686077d589e3ff777bf78c9fd6fcc5252
1,950
cpp
C++
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
8
2021-01-09T21:37:36.000Z
2022-01-05T09:27:13.000Z
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
null
null
null
src/harbour-hafenschau.cpp
black-sheep-dev/harbour-hafenschau
8384e769a0d6d5b85787e92565c475be9d2f37fa
[ "MIT" ]
1
2021-03-13T11:21:03.000Z
2021-03-13T11:21:03.000Z
#include <QtQuick> #include <sailfishapp.h> #include "api/apiinterface.h" #include "comments/commentsmodel.h" #include "comments/commentssortfiltermodel.h" #include "enums/enums.h" #include "news/newslistmodel.h" #include "news/newssortfiltermodel.h" #include "region/regionsmodel.h" #include "tools/datawriter.h" int main(int argc, char *argv[]) { // Disable crash guard and prefer egl for webgl. setenv("MOZ_DISABLE_CRASH_GUARD", "1", 1); setenv("MOZ_WEBGL_PREFER_EGL", "1", 1); // Set up QML engine. QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> v(SailfishApp::createView()); app->setApplicationName(QStringLiteral("Hafenschau")); app->setApplicationVersion(APP_VERSION); app->setOrganizationName(QStringLiteral("org.nubecula")); app->setOrganizationDomain(QStringLiteral("nubecula.org")); #ifndef QT_DEBUG auto uri = "org.nubecula.harbour.hafenschau"; #else #define uri "org.nubecula.harbour.hafenschau" #endif // register enums qmlRegisterUncreatableType<DeveloperOption>(uri, 1, 0, "DeveloperOption", ""); qmlRegisterUncreatableType<NewsType>(uri, 1, 0, "NewsType", ""); qmlRegisterUncreatableType<Ressort>(uri, 1, 0, "Ressort", ""); qmlRegisterUncreatableType<VideoQuality>(uri, 1, 0, "VideoQuality", ""); // register types qmlRegisterType<ApiInterface>(uri, 1, 0, "ApiInterface"); qmlRegisterType<CommentsModel>(uri, 1, 0, "CommentsModel"); qmlRegisterType<CommentsSortFilterModel>(uri, 1, 0, "CommentsSortFilterModel"); qmlRegisterType<DataWriter>(uri, 1, 0, "DataWriter"); qmlRegisterType<NewsListModel>(uri, 1, 0, "NewsListModel"); qmlRegisterType<NewsSortFilterModel>(uri, 1, 0, "NewsSortFilterModel"); qmlRegisterType<RegionsModel>(uri, 1, 0, "RegionsModel"); v->setSource(SailfishApp::pathTo("qml/harbour-hafenschau.qml")); v->show(); return app->exec(); }
34.821429
84
0.72
black-sheep-dev
6e81dcec9630a1c2e954cf272b68ab3816fb45b7
32,135
cpp
C++
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_resource_view.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
 #include "rhi_resource_view.d3d12.h" #include "rhi.d3d12.h" #include <array> #include <algorithm> namespace ngl { namespace rhi { // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- ConstantBufferViewDep::ConstantBufferViewDep() { } ConstantBufferViewDep::~ConstantBufferViewDep() { Finalize(); } bool ConstantBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } if (!check_bits(ResourceBindFlag::ConstantBuffer, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); view_ = descriptor_allocator->Allocate(); if (!view_.IsValid()) { std::cout << "[ERROR] ConstantBufferViewDep::Initialize" << std::endl; assert(false); return false; } D3D12_CONSTANT_BUFFER_VIEW_DESC view_desc = {}; view_desc.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); view_desc.SizeInBytes = p_buffer->GetBufferSize();// アライメント考慮サイズを指定している. auto handle = view_.cpu_handle; p_device->GetD3D12Device()->CreateConstantBufferView(&view_desc, handle); return true; } void ConstantBufferViewDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- VertexBufferViewDep::VertexBufferViewDep() { } VertexBufferViewDep::~VertexBufferViewDep() { Finalize(); } bool VertexBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } const auto& buffer_desc = p_buffer->GetDesc(); if (!check_bits(ResourceBindFlag::VertexBuffer, buffer_desc.bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); view_ = {}; view_.SizeInBytes = buffer_desc.element_count * buffer_desc.element_byte_size; view_.StrideInBytes = buffer_desc.element_byte_size; view_.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); return true; } void VertexBufferViewDep::Finalize() { view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- IndexBufferViewDep::IndexBufferViewDep() { } IndexBufferViewDep::~IndexBufferViewDep() { Finalize(); } bool IndexBufferViewDep::Initialize(BufferDep* p_buffer, const Desc& desc) { if (!p_buffer || !p_buffer->GetParentDevice()) { assert(false); return false; } const auto& buffer_desc = p_buffer->GetDesc(); if (!check_bits(ResourceBindFlag::IndexBuffer, buffer_desc.bind_flag)) { assert(false); return false; } auto&& p_device = p_buffer->GetParentDevice(); view_ = {}; view_.SizeInBytes = buffer_desc.element_count * buffer_desc.element_byte_size; view_.BufferLocation = p_buffer->GetD3D12Resource()->GetGPUVirtualAddress(); view_.Format = (buffer_desc.element_byte_size == 4) ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; return true; } void IndexBufferViewDep::Finalize() { view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- SamplerDep::SamplerDep() { } SamplerDep::~SamplerDep() { Finalize(); } bool SamplerDep::Initialize(DeviceDep* p_device, const Desc& desc) { if (!p_device) return false; auto&& descriptor_allocator = p_device->GetPersistentSamplerDescriptorAllocator();// Samplerは専用のAllocatorを利用. view_ = descriptor_allocator->Allocate(); if (!view_.IsValid()) return false; // Persistent上に作成. D3D12_SAMPLER_DESC d3ddesc = {}; d3ddesc.AddressU = ConvertTextureAddressMode(desc.AddressU); d3ddesc.AddressV = ConvertTextureAddressMode(desc.AddressV); d3ddesc.AddressW = ConvertTextureAddressMode(desc.AddressW); d3ddesc.BorderColor[0] = desc.BorderColor[0]; d3ddesc.BorderColor[1] = desc.BorderColor[1]; d3ddesc.BorderColor[2] = desc.BorderColor[2]; d3ddesc.BorderColor[3] = desc.BorderColor[3]; d3ddesc.ComparisonFunc = ConvertComparisonFunc(desc.ComparisonFunc); d3ddesc.Filter = ConvertTextureFilter(desc.Filter); d3ddesc.MaxAnisotropy = desc.MaxAnisotropy; d3ddesc.MaxLOD = desc.MaxLOD; d3ddesc.MinLOD = desc.MinLOD; d3ddesc.MipLODBias = desc.MipLODBias; p_device->GetD3D12Device()->CreateSampler(&(d3ddesc), view_.cpu_handle); return true; } void SamplerDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- namespace { /** texture dimension -> view dimension. */ ResourceDimension getTextureDimension(TextureType type, bool is_texture_array) { switch (type) { //case TextureType::Buffer: // assert(is_texture_array == false); // return ResourceDimension::Buffer; case TextureType::Texture1D: return (is_texture_array) ? ResourceDimension::Texture1DArray : ResourceDimension::Texture1D; case TextureType::Texture2D: return (is_texture_array) ? ResourceDimension::Texture2DArray : ResourceDimension::Texture2D; case TextureType::Texture2DMultisample: return (is_texture_array) ? ResourceDimension::Texture2DMSArray : ResourceDimension::Texture2DMS; case TextureType::Texture3D: assert(is_texture_array == false); return ResourceDimension::Texture3D; case TextureType::TextureCube: return (is_texture_array) ? ResourceDimension::TextureCubeArray : ResourceDimension::TextureCube; default: assert(false); return ResourceDimension::Unknown; } } /** view dimension to D3D12 view dimension. */ template<typename ViewType> ViewType getTextureViewDimension(ResourceDimension dimension); // for srv. template<> D3D12_SRV_DIMENSION getTextureViewDimension<D3D12_SRV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_SRV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_SRV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_SRV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_SRV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; case ResourceDimension::Texture3D: return D3D12_SRV_DIMENSION_TEXTURE3D; case ResourceDimension::TextureCube: return D3D12_SRV_DIMENSION_TEXTURECUBE; case ResourceDimension::TextureCubeArray: return D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; case ResourceDimension::AccelerationStructure: return D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; default: assert(false); return D3D12_SRV_DIMENSION_UNKNOWN; } } // for uav. template<> D3D12_UAV_DIMENSION getTextureViewDimension<D3D12_UAV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_UAV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_UAV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_UAV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture3D: return D3D12_UAV_DIMENSION_TEXTURE3D; default: assert(false); return D3D12_UAV_DIMENSION_UNKNOWN; } } // for dsv. template<> D3D12_DSV_DIMENSION getTextureViewDimension<D3D12_DSV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_DSV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_DSV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_DSV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_DSV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_DSV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; // TODO: Falcor previously mapped cube to 2D array. Not sure if needed anymore. //case ReflectionResourceType::Dimensions::TextureCube: return D3D12_DSV_DIMENSION_TEXTURE2DARRAY; default: assert(false); return D3D12_DSV_DIMENSION_UNKNOWN; } } // for rtv. template<> D3D12_RTV_DIMENSION getTextureViewDimension<D3D12_RTV_DIMENSION>(ResourceDimension dimension) { switch (dimension) { case ResourceDimension::Texture1D: return D3D12_RTV_DIMENSION_TEXTURE1D; case ResourceDimension::Texture1DArray: return D3D12_RTV_DIMENSION_TEXTURE1DARRAY; case ResourceDimension::Texture2D: return D3D12_RTV_DIMENSION_TEXTURE2D; case ResourceDimension::Texture2DArray: return D3D12_RTV_DIMENSION_TEXTURE2DARRAY; case ResourceDimension::Texture2DMS: return D3D12_RTV_DIMENSION_TEXTURE2DMS; case ResourceDimension::Texture2DMSArray: return D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; case ResourceDimension::Texture3D: return D3D12_RTV_DIMENSION_TEXTURE3D; default: assert(false); return D3D12_RTV_DIMENSION_UNKNOWN; } } // ------------------------------------------------------------------------------------------------------------------------------------------------- // Texture Dsv, Rtv, Uavの設定共通化. template<typename DescType> DescType createDsvRtvUavDescCommon(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { assert(p_texture); // Buffers should not get here uint32_t arrayMultiplier = (p_texture->GetType() == TextureType::TextureCube) ? 6 : 1; if (array_size + first_array_slice > p_texture->GetArraySize()) { array_size = p_texture->GetArraySize() - first_array_slice; } DescType desc = {}; desc.Format = ConvertResourceFormat(p_texture->GetFormat()); desc.ViewDimension = getTextureViewDimension<decltype(desc.ViewDimension)>(getTextureDimension(p_texture->GetType(), p_texture->GetArraySize() > 1)); switch (p_texture->GetType()) { case TextureType::Texture1D: if (p_texture->GetArraySize() > 1) { desc.Texture1DArray.ArraySize = array_size; desc.Texture1DArray.FirstArraySlice = first_array_slice; desc.Texture1DArray.MipSlice = mip_slice; } else { desc.Texture1D.MipSlice = mip_slice; } break; case TextureType::Texture2D: case TextureType::TextureCube: if (p_texture->GetArraySize() * arrayMultiplier > 1) { desc.Texture2DArray.ArraySize = array_size * arrayMultiplier; desc.Texture2DArray.FirstArraySlice = first_array_slice * arrayMultiplier; desc.Texture2DArray.MipSlice = mip_slice; } else { desc.Texture2D.MipSlice = mip_slice; } break; case TextureType::Texture2DMultisample: if constexpr (std::is_same_v<DescType, D3D12_DEPTH_STENCIL_VIEW_DESC> || std::is_same_v<DescType, D3D12_RENDER_TARGET_VIEW_DESC>) { if (p_texture->GetArraySize() > 1) { desc.Texture2DMSArray.ArraySize = array_size; desc.Texture2DMSArray.FirstArraySlice = first_array_slice; } } else { throw std::exception("Texture2DMultisample does not support UAV views"); } break; case TextureType::Texture3D: if constexpr (std::is_same_v<DescType, D3D12_UNORDERED_ACCESS_VIEW_DESC> || std::is_same_v<DescType, D3D12_RENDER_TARGET_VIEW_DESC>) { assert(p_texture->GetArraySize() == 1); desc.Texture3D.MipSlice = mip_slice; desc.Texture3D.FirstWSlice = 0; desc.Texture3D.WSize = p_texture->GetDepth(mip_slice); } else { throw std::exception("Texture3D does not support DSV views"); } break; default: assert(false); } return desc; } // Texture Dsv用. D3D12_DEPTH_STENCIL_VIEW_DESC createDsvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_DEPTH_STENCIL_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Rtv用. D3D12_RENDER_TARGET_VIEW_DESC createRtvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_RENDER_TARGET_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Uav用. D3D12_UNORDERED_ACCESS_VIEW_DESC createUavDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t first_array_slice, uint32_t array_size) { return createDsvRtvUavDescCommon<D3D12_UNORDERED_ACCESS_VIEW_DESC>(p_texture, mip_slice, first_array_slice, array_size); } // Texture Srv用. D3D12_SHADER_RESOURCE_VIEW_DESC createTextureSrvDesc(const TextureDep* p_texture, uint32_t mip_slice, uint32_t mip_count, uint32_t first_array_slice, uint32_t array_size) { assert(p_texture); D3D12_SHADER_RESOURCE_VIEW_DESC desc = {}; //If not depth, returns input format desc.Format = ConvertResourceFormat(depthToColorFormat(p_texture->GetFormat())); bool isTextureArray = p_texture->GetArraySize() > 1; desc.ViewDimension = getTextureViewDimension<D3D12_SRV_DIMENSION>(getTextureDimension(p_texture->GetType(), isTextureArray)); switch (p_texture->GetType()) { case TextureType::Texture1D: if (isTextureArray) { desc.Texture1DArray.MipLevels = mip_count; desc.Texture1DArray.MostDetailedMip = mip_slice; desc.Texture1DArray.ArraySize = array_size; desc.Texture1DArray.FirstArraySlice = first_array_slice; } else { desc.Texture1D.MipLevels = mip_count; desc.Texture1D.MostDetailedMip = mip_slice; } break; case TextureType::Texture2D: if (isTextureArray) { desc.Texture2DArray.MipLevels = mip_count; desc.Texture2DArray.MostDetailedMip = mip_slice; desc.Texture2DArray.ArraySize = array_size; desc.Texture2DArray.FirstArraySlice = first_array_slice; } else { desc.Texture2D.MipLevels = mip_count; desc.Texture2D.MostDetailedMip = mip_slice; } break; case TextureType::Texture2DMultisample: if (array_size > 1) { desc.Texture2DMSArray.ArraySize = array_size; desc.Texture2DMSArray.FirstArraySlice = first_array_slice; } break; case TextureType::Texture3D: assert(array_size == 1); desc.Texture3D.MipLevels = mip_count; desc.Texture3D.MostDetailedMip = mip_slice; break; case TextureType::TextureCube: if (array_size > 1) { desc.TextureCubeArray.First2DArrayFace = 0; desc.TextureCubeArray.NumCubes = array_size; desc.TextureCubeArray.MipLevels = mip_count; desc.TextureCubeArray.MostDetailedMip = mip_slice; } else { desc.TextureCube.MipLevels = mip_count; desc.TextureCube.MostDetailedMip = mip_slice; } break; default: assert(false); } desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; return desc; } struct BufferViewMode { enum Type : u32 { // Typed Buffer View. Typed, // Structured な buffer view. Structured, // 4 Byte per element な raw buffer view. ByteAddress }; }; D3D12_SHADER_RESOURCE_VIEW_DESC createBufferSrvDesc(const BufferDep* pBuffer // 初期化モード. , BufferViewMode::Type mode // 初期化モードTyped の場合の要素フォーマットタイプ. , ResourceFormat typed_format // 初期化モードStructured の場合の要素サイズ. , u32 structured_element_size , u32 element_offset, u32 element_count) { assert(pBuffer); D3D12_SHADER_RESOURCE_VIEW_DESC desc = {}; u32 bufferElementCount = 0; if (BufferViewMode::Typed == mode) { // Typed. bufferElementCount = pBuffer->getElementCount(); desc.Format = ConvertResourceFormat(typed_format); } else if (BufferViewMode::Structured == mode) { // Structured. bufferElementCount = pBuffer->getElementCount(); desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = structured_element_size; } else { // ByteAddress. bufferElementCount = pBuffer->getElementCount(); desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; } assert((element_offset + element_count) <= bufferElementCount); // Check range desc.Buffer.FirstElement = element_offset; desc.Buffer.NumElements = element_count; desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; return desc; } D3D12_UNORDERED_ACCESS_VIEW_DESC createBufferUavDesc(const BufferDep* p_buffer // 初期化モード. , BufferViewMode::Type mode // 初期化モードTyped の場合の要素フォーマットタイプ. , ResourceFormat typed_format // 初期化モードStructured の場合の要素サイズ. , u32 structured_element_size , u32 element_offset, u32 element_count) { assert(p_buffer); D3D12_UNORDERED_ACCESS_VIEW_DESC desc = {}; u32 bufferElementCount = 0; if (BufferViewMode::Typed == mode) { // Typed. bufferElementCount = p_buffer->getElementCount(); desc.Format = ConvertResourceFormat(typed_format); } else if (BufferViewMode::Structured == mode) { // Structured. bufferElementCount = p_buffer->getElementCount(); desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = structured_element_size; } else { // ByteAddress. bufferElementCount = p_buffer->getElementCount(); desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; } assert((element_offset + element_count) <= bufferElementCount); // Check range desc.Buffer.FirstElement = element_offset; desc.Buffer.NumElements = element_count; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; return desc; } } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- DepthStencilViewDep::DepthStencilViewDep() { } DepthStencilViewDep::~DepthStencilViewDep() { Finalize(); } bool DepthStencilViewDep::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device); assert(p_texture); if (!check_bits(ResourceBindFlag::DepthStencil, p_texture->GetBindFlag())) { assert(false); return false; } // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } // 専有HeapにDescriptor作成. D3D12_DEPTH_STENCIL_VIEW_DESC desc = createDsvDesc(p_texture, mip_slice, first_array_slice, array_size); p_device->GetD3D12Device()->CreateDepthStencilView(p_texture->GetD3D12Resource(), &desc, p_heap_->GetCPUDescriptorHandleForHeapStart()); return true; } void DepthStencilViewDep::Finalize() { p_heap_.Release(); } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- RenderTargetViewDep::RenderTargetViewDep() { } RenderTargetViewDep::~RenderTargetViewDep() { Finalize(); } bool RenderTargetViewDep::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device); assert(p_texture); if (!check_bits(ResourceBindFlag::RenderTarget, p_texture->GetBindFlag())) { assert(false); return false; } // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } // 専有HeapにDescriptor作成. { D3D12_RENDER_TARGET_VIEW_DESC desc = createRtvDesc(p_texture, mip_slice, first_array_slice, array_size); p_device->GetD3D12Device()->CreateRenderTargetView(p_texture->GetD3D12Resource(), &desc, p_heap_->GetCPUDescriptorHandleForHeapStart()); } return true; } // SwapChainからRTV作成. bool RenderTargetViewDep::Initialize(DeviceDep* p_device, SwapChainDep* p_swapchain, unsigned int buffer_index) { if (!p_device || !p_swapchain) return false; // 専有Heap確保. D3D12_DESCRIPTOR_HEAP_DESC heap_desc = {}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; heap_desc.NumDescriptors = 1; heap_desc.NodeMask = 0; heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if (FAILED(p_device->GetD3D12Device()->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&p_heap_)))) { std::cout << "[ERROR] Create DescriptorHeap" << std::endl; return false; } auto* buffer = p_swapchain->GetD3D12Resource(buffer_index); if (!buffer) { std::cout << "[ERROR] Invalid Buffer Index" << std::endl; return false; } auto handle_head = p_heap_->GetCPUDescriptorHandleForHeapStart(); p_device->GetD3D12Device()->CreateRenderTargetView(buffer, nullptr, handle_head); return true; } void RenderTargetViewDep::Finalize() { p_heap_.Release(); } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- UnorderedAccessView::UnorderedAccessView() { } UnorderedAccessView::~UnorderedAccessView() { Finalize(); } template<typename ResourceType> bool _Initialize(DeviceDep* p_device, const ResourceType* p_buffer, const D3D12_UNORDERED_ACCESS_VIEW_DESC& desc, PersistentDescriptorInfo& out_desc_info) { // Descriptor確保. auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); out_desc_info = descriptor_allocator->Allocate(); if (!out_desc_info.IsValid()) { std::cout << "[ERROR] ShaderResourceViewDep::InitializeAsStructured" << std::endl; assert(false); return false; } constexpr ID3D12Resource* p_counter_resource = nullptr; p_device->GetD3D12Device()->CreateUnorderedAccessView(p_buffer->GetD3D12Resource(), p_counter_resource, &desc, out_desc_info.cpu_handle); return true; } // TextureのView. bool UnorderedAccessView::Initialize(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 first_array_slice, u32 array_size) { assert(p_device && p_texture); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_texture->GetBindFlag())) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createUavDesc(p_texture, mip_slice, first_array_slice, array_size); return _Initialize(p_device, p_texture, desc, view_); } // BufferのStructuredBufferView. bool UnorderedAccessView::InitializeAsStructured(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_size, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::Structured, {}, element_size, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのTypedBufferView. bool UnorderedAccessView::InitializeAsTyped(DeviceDep* p_device, const BufferDep* p_buffer, ResourceFormat format, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::Typed, format, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのByteAddressBufferView. bool UnorderedAccessView::InitializeAsRaw(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!check_bits(ResourceBindFlag::UnorderedAccess, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_UNORDERED_ACCESS_VIEW_DESC desc = createBufferUavDesc(p_buffer, BufferViewMode::ByteAddress, {}, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } void UnorderedAccessView::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------------------------------------- ShaderResourceViewDep::ShaderResourceViewDep() { } ShaderResourceViewDep::~ShaderResourceViewDep() { Finalize(); } template<typename ResourceType> bool _Initialize(DeviceDep* p_device, const ResourceType* p_buffer, const D3D12_SHADER_RESOURCE_VIEW_DESC& desc, PersistentDescriptorInfo& out_desc_info) { // Descriptor確保. auto&& descriptor_allocator = p_device->GetPersistentDescriptorAllocator(); out_desc_info = descriptor_allocator->Allocate(); if (!out_desc_info.IsValid()) { std::cout << "[ERROR] ShaderResourceViewDep::InitializeAsStructured" << std::endl; assert(false); return false; } p_device->GetD3D12Device()->CreateShaderResourceView(p_buffer->GetD3D12Resource(), &desc, out_desc_info.cpu_handle); return true; } // TextureのView. bool ShaderResourceViewDep::InitializeAsTexture(DeviceDep* p_device, const TextureDep* p_texture, u32 mip_slice, u32 mip_count, u32 first_array_slice, u32 array_size) { assert(p_device && p_texture); if (!p_device || !p_texture) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_texture->GetBindFlag())) { assert(false); return false; } // clamp mip, array range. if (mip_slice >= p_texture->GetMipCount()) { mip_slice = p_texture->GetMipCount() - 1; mip_count = 1; } else if ((mip_count == 0) || (mip_count > p_texture->GetMipCount() - mip_slice)) { mip_count = p_texture->GetMipCount() - mip_slice; } if (first_array_slice >= p_texture->GetArraySize()) { first_array_slice = p_texture->GetArraySize() - 1; array_size = 1; } else if ((array_size == 0) || (array_size > p_texture->GetArraySize() - first_array_slice)) { array_size = p_texture->GetArraySize() - first_array_slice; } // Desc生成. auto desc = createTextureSrvDesc(p_texture, mip_slice, mip_count, first_array_slice, array_size); return _Initialize(p_device, p_texture, desc, view_); } // BufferのStructuredBufferView. bool ShaderResourceViewDep::InitializeAsStructured(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_size, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::Structured, {}, element_size, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのTypedBufferView. bool ShaderResourceViewDep::InitializeAsTyped(DeviceDep* p_device, const BufferDep* p_buffer, ResourceFormat format, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::Typed, format, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } // BufferのByteAddressBufferView. bool ShaderResourceViewDep::InitializeAsRaw(DeviceDep* p_device, const BufferDep* p_buffer, u32 element_offset, u32 element_count) { assert(p_device && p_buffer); if (!p_device || !p_buffer) return false; if (!check_bits(ResourceBindFlag::ShaderResource, p_buffer->GetDesc().bind_flag)) { assert(false); return false; } D3D12_SHADER_RESOURCE_VIEW_DESC desc = createBufferSrvDesc(p_buffer, BufferViewMode::ByteAddress, {}, {}, element_offset, element_count); return _Initialize(p_device, p_buffer, desc, view_); } void ShaderResourceViewDep::Finalize() { auto&& descriptor_allocator = view_.allocator; if (descriptor_allocator) { descriptor_allocator->Deallocate(view_); } view_ = {}; } // ------------------------------------------------------------------------------------------------------------------------------------------------- } }
35.390969
173
0.647394
nagakagachi
6e8df8ed79087855af3e93aa0c25fdda8d0629db
11,956
hpp
C++
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
5
2018-03-24T02:40:36.000Z
2020-08-31T02:50:49.000Z
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
9
2017-11-22T11:09:52.000Z
2018-03-03T09:55:01.000Z
include/frechetrange/detail/bb/spatial_index.hpp
TWTDIG/frechetrange
b5b30708a7d2ec181ed6a870923542e286f894ab
[ "MIT" ]
3
2017-11-21T07:29:32.000Z
2019-12-22T15:50:47.000Z
#ifndef BB_SPATIAL_INDEX_HPP #define BB_SPATIAL_INDEX_HPP #include <algorithm> // for std::max and std::min #include <array> #include <cmath> // for std::sqrt and std::abs #include <memory> // for std::unique_ptr #include <utility> // for std::pair #include <vector> #include "frechet_distance.hpp" namespace frechetrange { namespace detail { namespace bb { // TODO: multidimensional // A point in the n-dimensional space template <size_t dimensions> using nd_point = std::array<distance_t, dimensions>; // ----------- quadtree ----------- template <size_t dimensions> distance_t nd_point_dist(const nd_point<dimensions> &a, const nd_point<dimensions> &b); template <> distance_t nd_point_dist(const nd_point<8> &a, const nd_point<8> &b) { distance_t result = 0; for (size_t i = 0; i < 4; i += 2) { result = std::max( result, std::sqrt(sqr(a[i] - b[i]) + sqr(a[i + 1] - b[i + 1]))); } for (size_t i = 4; i < 8; ++i) { result = std::max(result, std::abs(a[i] - b[i])); } return result; } constexpr long long constexpr_power(long long base, long long exponent) { return (exponent == 0) ? 1 : base * constexpr_power(base, exponent - 1); } // Returns true iff the i-th lowest bit (starting at 0) in number is 1. constexpr bool bit_is_set(long long number, size_t i) { return (number & (static_cast<size_t>(1) << i)) != 0; } template <size_t dimensions, typename element, size_t max_elments_per_node> struct quadtree_node { typedef nd_point<dimensions> point; std::array<std::unique_ptr<quadtree_node>, constexpr_power(2, dimensions)> _children; point _min_coords, _max_coords; std::vector<std::pair<point, element>> _elements; bool _has_children; quadtree_node(const point &min_coords, const point &max_coords) : _children(), _min_coords(min_coords), _max_coords(max_coords), _elements(), _has_children(false) {} std::vector<element> get(const point &center, distance_t radius) const { std::vector<element> result; get_recursive(center, radius, result); return result; } void get_recursive(const point &center, distance_t radius, std::vector<element> &result) const { bool covered = true; for (size_t i = 0; i < dimensions; ++i) { if (_min_coords[i] > center[i] + radius || _max_coords[i] < center[i] - radius) { return; // circle does not intersect current area } if (_min_coords[i] < center[i] - radius || _max_coords[i] > center[i] + radius) { covered = false; } } if (_has_children && !covered) { for (auto &child : _children) { child->get_recursive(center, radius, result); } } else { for (const std::pair<point, element> &e : _elements) { if (nd_point_dist(center, e.first) <= radius) { result.push_back(e.second); } } } } size_t get_child_id(const point &position) const { size_t result = 0; for (int i = dimensions - 1; i >= 0; --i) { bool high = position[i] >= (_min_coords[i] + _max_coords[i]) / 2; result = 2 * result + high; } return result; } void add(const element &e, const point &position) { _elements.push_back(std::make_pair(position, e)); if (_has_children) { _children[get_child_id(position)]->add(e, position); } else { if (_elements.size() > max_elments_per_node) split(); } } void split() { bool splittable = false; for (size_t i = 1; i < _elements.size(); ++i) { if (_elements[i].first != _elements[i - 1].first) { splittable = true; break; } } if (!splittable) return; for (size_t i = 0; i < _children.size(); ++i) { point mini = _min_coords, maxi = _max_coords; for (size_t j = 0; j < dimensions; ++j) { distance_t center = (_min_coords[j] + _max_coords[j]) / 2; if (bit_is_set(i, j)) { mini[j] = center; } else { maxi[j] = center; } } _children[i] = std::unique_ptr<quadtree_node>(new quadtree_node(mini, maxi)); } _has_children = true; for (auto &e : _elements) { _children[get_child_id(e.first)]->add(e.second, e.first); } } }; template <size_t dimensions, typename element, size_t max_elments_per_node = constexpr_power(2, dimensions)> using quadtree = quadtree_node<dimensions, element, max_elments_per_node>; // ----------- spatial_index ----------- template <size_t dimensions, typename trajectory, typename get_coordinate, typename squared_distance = euclidean_distance_sqr<dimensions, get_coordinate>> class spatial_index { public: spatial_index(const squared_distance &dist2 = squared_distance()) : _q({{MIN_X, MIN_Y, MIN_X, MIN_Y, MIN_X, MIN_Y, MIN_X, MIN_Y}}, {{MAX_X, MAX_Y, MAX_X, MAX_Y, MAX_X, MAX_Y, MAX_X, MAX_Y}}), _curves(), _dist2(dist2), _frechet_dist(dist2) {} size_t size() const { return _curves.size(); } void insert(const trajectory &t) { _q.add(_curves.size(), get_position(t)); _curves.emplace_back(t, _dist2); } // Returns the ids of all trajectories that may have frechet distance d or // less. // The result may however contain some whose frechet distance to c is too // large. std::vector<const trajectory *> range_query(const trajectory &t, distance_t d) const { std::vector<const trajectory *> result_set; auto push_back_result = [&result_set](const trajectory &t) { result_set.push_back(&t); }; range_query(t, d, push_back_result); return result_set; } template <typename output_func> void range_query(const trajectory &t, distance_t d, output_func &output) const { // TODO: don't copy t curve<trajectory> c(t, _dist2); std::vector<size_t> potential_curves = _q.get(get_position(t), d); for (size_t i : potential_curves) { const curve<trajectory> &c2 = _curves[i]; if (get_frechet_distance_upper_bound(t, c2.get_trajectory()) <= sqr(d)) { output(c2.get_trajectory()); } else if (negfilter(c, c2, d)) { continue; } else if (_frechet_dist.is_bounded_by(c, c2, d)) { output(c2.get_trajectory()); } } } private: static constexpr distance_t MIN_X = -1e18l, MIN_Y = -1e18l, MAX_X = 1e18l, MAX_Y = 1e18l; quadtree<8, size_t> _q; // first x, first y, last x, last y, min x, min y, max x, max y std::vector<curve<trajectory>> _curves; squared_distance _dist2; frechet_distance<dimensions, get_coordinate, squared_distance> _frechet_dist; template <typename point_t> distance_t dist(point_t &p, point_t &q) const { return std::sqrt(_dist2(p, q)); } nd_point<8> get_position(const trajectory &t) const { size_t last = t.size() - 1; nd_point<8> p = {{get_coordinate::template get<0>(t[0]), get_coordinate::template get<1>(t[0]), get_coordinate::template get<0>(t[last]), get_coordinate::template get<1>(t[last]), MAX_X, MAX_Y, MIN_X, MIN_Y}}; for (size_t i = 0; i <= last; ++i) { p[4] = std::min(p[4], get_coordinate::template get<0>(t[i])); p[5] = std::min(p[5], get_coordinate::template get<1>(t[i])); p[6] = std::max(p[6], get_coordinate::template get<0>(t[i])); p[7] = std::max(p[7], get_coordinate::template get<1>(t[i])); } return p; } // ----------- filters ----------- /* * Calculates an upper bound for the squared Frechet distance of a and b by * guessing a matching between a and b * O(a.size() + b.size()) */ distance_t get_frechet_distance_upper_bound(const trajectory &a, const trajectory &b) const { distance_t sqrd_dist = _dist2(a[a.size() - 1], b[b.size() - 1]); size_t pos_a = 0, pos_b = 0; while (pos_a + pos_b < a.size() + b.size() - 2) { sqrd_dist = std::max(sqrd_dist, _dist2(a[pos_a], b[pos_b])); if (pos_a == a.size() - 1) ++pos_b; else if (pos_b == b.size() - 1) ++pos_a; else { distance_t dist_a = _dist2(a[pos_a + 1], b[pos_b]); distance_t dist_b = _dist2(a[pos_a], b[pos_b + 1]); distance_t dist_both = _dist2(a[pos_a + 1], b[pos_b + 1]); if (dist_a < dist_b && dist_a < dist_both) { ++pos_a; } else if (dist_b < dist_both) { ++pos_b; } else { ++pos_a; ++pos_b; } } } return sqrd_dist; } /* * Returns (a discrete approximation of) the first point c[j] on c, with j * >= * i, that is within distance d of point p. */ template <typename point_t> size_t nextclosepoint(const curve<trajectory> &c, size_t i, const point_t &p, distance_t d) const { const trajectory &t = c.get_trajectory(); size_t delta = 1; size_t k = i; while (true) { if (k == t.size() - 1) { if (_dist2(t[k], p) <= sqr(d)) { return k; } else { return c.size(); } } else { delta = std::min(delta, t.size() - 1 - k); if (dist(p, t[k]) - c.curve_length(k, k + delta) > d) { k += delta; delta *= 2; } else if (delta > 1) { delta /= 2; } else { return k; } } } } /* * Tries to show that the Frechet distance of a and b is more than d. * Returns * true if a proof is found. */ bool negfilter(const curve<trajectory> &c1, const curve<trajectory> &c2, distance_t d) const { for (size_t delta = std::max(c1.size(), c2.size()) - 1; delta >= 1; delta /= 2) { size_t i = 0; for (size_t j = 0; j < c2.size(); j += delta) { i = nextclosepoint(c1, i, c2.get_trajectory()[j], d); if (i >= c1.size()) { return true; } } size_t j = 0; for (size_t i = 0; i < c1.size(); i += delta) { j = nextclosepoint(c2, j, c1.get_trajectory()[i], d); if (j >= c2.size()) { return true; } } } return false; } }; } // namespace bb } // namespace detail } // namespace frechetrange #endif
34.655072
93
0.505353
TWTDIG
6e8ed7dc5bcc95a9ffc0a61de4edc4429711ae1e
4,144
inl
C++
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
6
2019-06-16T22:20:55.000Z
2021-11-13T17:16:16.000Z
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
null
null
null
include/as/as-mat.inl
pr0g/as
5698ded06abca884385b9deebe8a2e702e8a66a8
[ "MIT" ]
1
2020-04-11T14:24:13.000Z
2020-04-11T14:24:13.000Z
namespace as { template<typename T, index d> AS_API mat<T, d> mat_identity() { mat<T, d> identity{}; for (index i = 0; i < mat<T, d>::size(); i += d + 1) { identity[i] = T(1.0); } return identity; } template<typename T, index d> AS_API constexpr index mat<T, d>::dim() { return d; } template<typename T, index d> AS_API constexpr index mat<T, d>::size() { return d * d; } template<typename T, index d> AS_API constexpr index mat<T, d>::rows() { return mat<T, d>::dim(); } template<typename T, index d> AS_API constexpr index mat<T, d>::cols() { return mat<T, d>::dim(); } template<typename T, index d> AS_API mat<T, d> mat<T, d>::identity() { return mat_identity<T, d>(); } template<typename T, index d> AS_API constexpr T& mat<T, d>::operator[](const index i) & { return elem_rc[i]; } template<typename T, index d> AS_API constexpr const T& mat<T, d>::operator[](const index i) const& { return elem_rc[i]; } template<typename T, index d> AS_API constexpr const T mat<T, d>::operator[](const index i) && { return elem_rc[i]; } template<typename T, index d> AS_API const mat<T, d> operator*(const mat<T, d>& lhs, const mat<T, d>& rhs) { mat<T, d> result; #ifdef AS_COL_MAJOR for (index col = 0; col < d; ++col) { for (index row = 0; row < d; ++row) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += lhs[row + d * step] * rhs[col * d + step]; } result[col * d + row] = value; } } #elif defined AS_ROW_MAJOR for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += lhs[row * d + step] * rhs[col + d * step]; } result[row * d + col] = value; } } #endif // AS_ROW_MAJOR ? AS_COL_MAJOR return result; } template<typename T, index d> #ifdef AS_ROW_MAJOR AS_API const vec<T, d> operator*(const vec<T, d>& v, const mat<T, d>& m) #elif defined AS_COL_MAJOR AS_API const vec<T, d> operator*(const mat<T, d>& m, const vec<T, d>& v) #endif // AS_ROW_MAJOR ? AS_COL_MAJOR { vec<T, d> result; for (index i = 0; i < d; ++i) { auto value = T(0.0); for (index step = 0; step < d; ++step) { value += v[step] * m[i + step * d]; } result[i] = value; } return result; } template<typename T, index d> AS_API constexpr const mat<T, d> operator*(const mat<T, d>& m, const T scalar) { mat<T, d> result{m}; result *= scalar; return result; } template<typename T, index d> AS_API constexpr mat<T, d>& operator*=(mat<T, d>& m, const T scalar) { for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { m[row * d + col] *= scalar; } } return m; } template<typename T, index d> AS_API constexpr bool operator==(const mat<T, d>& lhs, const mat<T, d>& rhs) { return !(lhs != rhs); } template<typename T, index d> AS_API constexpr bool operator!=(const mat<T, d>& lhs, const mat<T, d>& rhs) { for (index row = 0; row < d; ++row) { for (index col = 0; col < d; ++col) { const index lookup = row * d + col; if (lhs[lookup] != rhs[lookup]) { return true; } } } return false; } template<typename T, index d> AS_API constexpr subscript_iterator<mat<T, d>> begin(mat<T, d>& m) { return subscript_iterator<mat<T, d>>(m, 0); } template<typename T, index d> AS_API constexpr subscript_iterator<mat<T, d>> end(mat<T, d>& m) { return subscript_iterator<mat<T, d>>(m, mat<T, d>::size()); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> begin(const mat<T, d>& m) { return subscript_const_iterator<mat<T, d>>(m, 0); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> end(const mat<T, d>& m) { return subscript_const_iterator<mat<T, d>>(m, mat<T, d>::size()); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> cbegin(const mat<T, d>& m) { return begin(m); } template<typename T, index d> AS_API constexpr subscript_const_iterator<mat<T, d>> cend(const mat<T, d>& m) { return end(m); } } // namespace as
22.521739
79
0.610521
pr0g
6e8fa2fb56d06ebf06acaaa2e29e4db377dfd422
1,196
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR/List`1_Reverse/cpp/source.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet1> using namespace System; using namespace System::Collections::Generic; void main() { List<String^>^ dinosaurs = gcnew List<String^>(); dinosaurs->Add("Pachycephalosaurus"); dinosaurs->Add("Parasauralophus"); dinosaurs->Add("Mamenchisaurus"); dinosaurs->Add("Amargasaurus"); dinosaurs->Add("Coelophysis"); dinosaurs->Add("Oviraptor"); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } dinosaurs->Reverse(); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } dinosaurs->Reverse(1, 4); Console::WriteLine(); for each(String^ dinosaur in dinosaurs) { Console::WriteLine(dinosaur); } } /* This code example produces the following output: Pachycephalosaurus Parasauralophus Mamenchisaurus Amargasaurus Coelophysis Oviraptor Oviraptor Coelophysis Amargasaurus Mamenchisaurus Parasauralophus Pachycephalosaurus Oviraptor Parasauralophus Mamenchisaurus Amargasaurus Coelophysis Pachycephalosaurus */ // </Snippet1>
18.4
54
0.664716
hamarb123
6e9167bc0867048bff0f11a078a6b739187a31a6
8,478
cpp
C++
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CEVPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
14
2018-03-16T10:08:12.000Z
2021-04-13T21:11:53.000Z
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CryVideoPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
4
2018-03-06T01:52:36.000Z
2021-04-26T07:25:07.000Z
Module/Components/TextureVideoPlayerComponent.cpp
afrostalin/CEVPlayer
5e91493a11b4c294d3582b80dae4ea2d95856a7d
[ "BSL-1.0" ]
8
2018-06-14T13:09:13.000Z
2021-04-13T21:11:57.000Z
// Copyright (C) 2017-2020 Ilya Chernetsov. All rights reserved. Contacts: <[email protected]> // License: https://github.com/afrostalin/CEVPlayer/blob/master/LICENSE #include "StdAfx.h" #include "PluginEnv.h" #include "TextureVideoPlayerComponent.h" #include "Video/TextureVideoQueue.h" #include <CrySchematyc/Utils/EnumFlags.h> #include <CrySchematyc/Env/Elements/EnvComponent.h> #include <CrySchematyc/Env/Elements/EnvFunction.h> #include <CrySchematyc/Env/Elements/EnvSignal.h> #include <CrySchematyc/ResourceTypes.h> #include <CrySchematyc/MathTypes.h> #include <CrySchematyc/IObject.h> namespace CEVPlayer { static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnStartPlaySignal>& desc) { desc.SetGUID("672B590C-E387-4357-BDD0-A3C3884277C5"_cry_guid); desc.SetLabel("OnStartPlay"); desc.SetDescription("Executed when video start playing to texture"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnPausedSignal>& desc) { desc.SetGUID("92C48065-FC02-4CD3-A609-AF6384498627"_cry_guid); desc.SetLabel("OnPaused"); desc.SetDescription("Executed when video paused"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnResumedSignal>& desc) { desc.SetGUID("176C5938-389B-470F-886D-CD13A82D9744"_cry_guid); desc.SetLabel("OnResumed"); desc.SetDescription("Executed when video resumed"); } static void ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent::SOnStoppedSignal>& desc) { desc.SetGUID("7F0EFF91-47B4-45F1-982E-F15613C9D4FB"_cry_guid); desc.SetLabel("OnStopped"); desc.SetDescription("Executed when video stopped"); } void CTextureVideoPlayerComponent::Register(Schematyc::CEnvRegistrationScope& componentScope) { { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Play, "1240FF98-3145-48BD-B282-4AEC7D647C1D"_cry_guid, "Play"); pFunction->SetDescription("Start play video to texture"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); pFunction->BindInput(1, 'val1', "VideoFilename", "Video file name without folder and extension (e.g. logo)"); pFunction->BindInput(2, 'val2', "OutputTextureName", "Output texture name for using in materials. Can't be null"); pFunction->BindInput(3, 'val3', "IsPreloaded", "File will be preloaded in memory before playing"); pFunction->BindInput(4, 'val4', "IsLooped", "Video can be looped here"); pFunction->BindInput(5, 'val5', "CanPlayInEditor", "Video can be play in editor"); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Pause, "33121C57-8DDE-4845-9357-F4E34F6E77C9"_cry_guid, "Pause"); pFunction->SetDescription("Pause current playing video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Resume, "B6D31737-C79E-4A36-874D-A685A7C6E9FC"_cry_guid, "Resume"); pFunction->SetDescription("Resume paused video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } { auto pFunction = SCHEMATYC_MAKE_ENV_FUNCTION(&CTextureVideoPlayerComponent::Stop, "1EA6B0BD-4ED5-4C66-9AE0-1CC92DAD6AF7"_cry_guid, "Stop"); pFunction->SetDescription("Stop playing video"); pFunction->SetFlags(Schematyc::EEnvFunctionFlags::Construction); componentScope.Register(pFunction); } componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnStartPlaySignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnPausedSignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnResumedSignal)); componentScope.Register(SCHEMATYC_MAKE_ENV_SIGNAL(CTextureVideoPlayerComponent::SOnStoppedSignal)); } void CTextureVideoPlayerComponent::ReflectType(Schematyc::CTypeDesc<CTextureVideoPlayerComponent>& desc) { desc.SetGUID("1AE1AB31-50A4-4D83-BAF0-FFB48CABF0B2"_cry_guid); desc.SetEditorCategory("Video"); desc.SetLabel("TextureVideoPlayer"); desc.SetDescription("Play video to texture"); desc.SetIcon("icons:General/Camera.ico"); desc.SetComponentFlags({ IEntityComponent::EFlags::Attach, IEntityComponent::EFlags::ClientOnly }); desc.AddMember(&CTextureVideoPlayerComponent::m_IsAutoPlay, 'auto', "autoplay", "IsAutoPlay", "If set it to true - video start play when game started", false); desc.AddMember(&CTextureVideoPlayerComponent::m_VideoFileName, 'vide', "videofile", "VideoFileName", "Video file name witout folder and extension", ""); desc.AddMember(&CTextureVideoPlayerComponent::m_OutputFileName, 'text', "outtexture", "OutputTextureName", "Output texture name for using in materials. Can't be null. Need start for $ simbol. (e.g. $videoplayer_1)", ""); desc.AddMember(&CTextureVideoPlayerComponent::m_IsPreloaded, 'prel', "preloaded", "IsPreloaded", "If set it to true - before playing video his will be loaded in memory", true); desc.AddMember(&CTextureVideoPlayerComponent::m_IsLooped, 'loop', "looped", "IsLooped", "If set it to true - video will be looped", false); desc.AddMember(&CTextureVideoPlayerComponent::m_IsCanPlayInEditor, 'edit', "canplayineditor", "IsCanPlayInEditor", "If set it to true - video can be played in editor mode", false); } void CTextureVideoPlayerComponent::Initialize() { } void CTextureVideoPlayerComponent::OnShutDown() { Stop(); } Cry::Entity::EventFlags CTextureVideoPlayerComponent::GetEventMask() const { return EEntityEvent::GameplayStarted; } void CTextureVideoPlayerComponent::ProcessEvent(const SEntityEvent& event) { switch (event.event) { case EEntityEvent::GameplayStarted: { if (m_IsAutoPlay) { Play(m_VideoFileName, m_OutputFileName, m_IsPreloaded, m_IsLooped, m_IsCanPlayInEditor); } break; } default: break; } } void CTextureVideoPlayerComponent::Play(Schematyc::CSharedString videoFile, Schematyc::CSharedString outputTexture, bool preload, bool looped, bool canPlayInEditor) { if (videoFile.empty()) { LogError("<CTextureVideoPlayerComponent> Can't play video, because video file name empty, check you component settings and try again!"); return; } if (outputTexture.empty()) { LogError("<CTextureVideoPlayerComponent> Can't play video, because output texture name empty, check you component settings and try again!"); return; } if (gEnv->IsEditor() && !canPlayInEditor) { LogError("<CTextureVideoPlayerComponent> Can't play video, because playing blocking in editor mode!"); return; } if (!m_IsAutoPlay) { m_VideoFileName = videoFile; m_OutputFileName = outputTexture; m_IsPreloaded = preload; m_IsLooped = looped; m_IsCanPlayInEditor = canPlayInEditor; } if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->PlayVideo(this, videoFile.c_str(), outputTexture.c_str(), preload, looped); } } void CTextureVideoPlayerComponent::Pause() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->PauseVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::Resume() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->ResumeVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::Stop() { if (mEnv != nullptr && mEnv->pTextureVideoQueue != nullptr) { mEnv->pTextureVideoQueue->StopVideo(m_OutputFileName.c_str()); } } void CTextureVideoPlayerComponent::OnVideoPlayerEvent(const char* videoFileName, EVideoPlayerEvents event) { if (gEnv->pSystem != nullptr && gEnv->pSystem->IsQuitting()) { return; } Schematyc::IObject* const pSchematycObject = m_pEntity->GetSchematycObject(); if (pSchematycObject == nullptr) { return; } switch (event) { case EVideoPlayerEvents::OnPlay: pSchematycObject->ProcessSignal(SOnStartPlaySignal(), GetGUID()); break; case EVideoPlayerEvents::OnPause: pSchematycObject->ProcessSignal(SOnPausedSignal(), GetGUID()); break; case EVideoPlayerEvents::OnResume: pSchematycObject->ProcessSignal(SOnResumedSignal(), GetGUID()); break; case EVideoPlayerEvents::OnStop: pSchematycObject->ProcessSignal(SOnStoppedSignal(), GetGUID()); break; default: break; } } }
37.184211
222
0.760085
afrostalin
6e98d6768c8266328d120379214e497a368e85b9
4,383
cpp
C++
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
relationships/unify_years.cpp
tehora/phd-sourcecodes
b8c9be03b6de012b886e3d3f43c9d179ec2d701b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <ghutils.h> #include <vector> #include <map> FILE *fmyids = fopen("myids.txt", "wt"); FILE *fstats = fopen("stats.txt", "wt"); #define MAXLINE 1000000000 typedef unsigned char uchr; map <pair<int, int>, int > graf; struct osoba { string xlogin; uchr rozmiar; uchr padding; uchr org1, org2, usr1, usr2; uchr goodtime; uchr badtime; short reg; uchr ineryx, padding2; osoba() { rozmiar = org1 = org2 = usr1 = usr2 = goodtime = badtime = padding = 0; ineryx = padding2 = 0; reg = 32767; } }; map<string, int> grouptomyid; vector<osoba> osoby; int qosoby = 1; int alledges = 0; int nextid() { int v = qosoby++; osoby.resize(qosoby); return v; } bool nomore = false; int getmyid(const string& login) { string l = tolower(login); if(nomore && !grouptomyid.count(l)) return -1; int& gtm(grouptomyid[l]); if(gtm == 0 && !nomore) { gtm = nextid(); osoby[gtm].xlogin = login; fprintf(fmyids, "%d;%s\n", gtm, login.c_str()); } return gtm; } int main(int argc, char **argv) { // printf("ed = %d\n", (int) sizeof(edge)); return 0; osoby.resize(1); {csvparser in("../../agregaty/ktoto2.csv"); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[1]); grouptomyid[tolower(in[2])] = id; osoby[id].rozmiar++; } } fclose(fmyids); {csvparser in("../../id_eryx.csv", ','); in.next(); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[2]); int aid = tonum(in[0]); auto& o(osoby[id]); if(in[1] == "user") o.usr1++; else if(in[1] == "organization") o.org1++; else fprintf(fstats, "unknown type %s in crawl\n", in[1].c_str()); if(aid <= 2) o.reg = 2007*16+13; else if(aid <= 43569) o.reg = 2008*16+13; else if(aid <= 174849) o.reg = 2009*16+13; else if(aid <= 543015) o.reg = 2010*16+13; else if(aid <= 1296987) o.reg = 2011*16+13; else if(aid <= 3161234) o.reg = 2012*16+13; else if(aid <= 6295257) o.reg = 2013*16+13; else if(aid <=10361315) o.reg = 2014*16+13; else o.reg = 2015*16+13; o.ineryx++; } } {csvparser in("../../rawdata/ght/users.csv", ','); in.next(); while(in.next()) { if(in.linenumber > MAXLINE) break; if(in.fields != 12) fprintf(fstats, "bad fieldcount (%d) in users\n", in.fields); else { int id = getmyid(in[1]); auto& o(osoby[id]); if(in[5] == "1") in[4] = "ORG"; if(in[6] == "1") in[4] = "ORG"; if(in[4] == "USR") o.usr2++; else if(in[4] == "ORG") o.org2++; else fprintf(fstats, "unknown type %s in users\n", in[4].c_str()); string srok = in[3].substr(0, 4); string smon = in[3].substr(5, 2); int rok = atoi(srok.c_str()); int mon = atoi(smon.c_str()); int reg = rok * 16 + mon; if(reg < o.reg || ((o.reg&15) == 13)) o.reg = reg; if(rok >= 2000 && rok <= 2017) o.goodtime++; else if(rok >= 2017) o.badtime++; else fprintf(fstats, "unknown date %s in users\n", in[3].c_str()); } } } fprintf(fstats, "qosoby = %d\n", qosoby); fflush(fstats); {csvparser in(argv[1]); in.next(); while(in.next()) { if(in.fields < 3) continue; if(in.linenumber > MAXLINE) break; int id_source = getmyid(in[1]); int id_target = getmyid(in[2]); cout <<id_source <<";" <<id_target <<endl; if (graf.count(make_pair(id_source,id_target))==0) { graf[make_pair(id_source, id_target)]=tonum(in[0]); } else { if (graf[make_pair(id_source, id_target)] > tonum(in[0])) { graf[make_pair(id_source, id_target)] = tonum(in[0]); } } }} {csvparser in("../../agregaty/ktoto2.csv"); FILE *f = fopen("../../agregaty/my-ktoto.csv", "wt"); while(in.next() && in.fields == 3) { if(in.linenumber > MAXLINE) break; int id = getmyid(in[1]); if(id >= 0) fprintf(f, "%d;%s\n", id, in[2].c_str()); } fclose(f); } fclose(fstats); ofstream of1(argv[2]); for ( auto& edge: graf) { of1 <<edge.second <<";" <<edge.first.first <<";" <<edge.first.second << "\n"; } return 0; }
27.055556
86
0.534337
tehora
6ea5479684aea0946f1f98de049a17fedcbb670c
193
cc
C++
test/check_module.cc
respu/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
2
2015-11-05T09:08:04.000Z
2016-02-09T23:26:00.000Z
test/check_module.cc
yggchan/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
null
null
null
test/check_module.cc
yggchan/libposix
27681383e5d3e19687d7fba23d97166beeeece13
[ "Unlicense" ]
null
null
null
/* This is free and unencumbered software released into the public domain. */ #include "catch.hpp" #include <posix++/module.h> /* for posix::module */ TEST_CASE("test_module") { // TODO }
19.3
77
0.683938
respu
6ea7712832a3df3014e2fcb66d4768d8068e545e
737
cpp
C++
week2/man_dog.cpp
aviiciii/iitb-exercises
e078e28fceb87eecc747272abd410e7279b22a97
[ "MIT" ]
null
null
null
week2/man_dog.cpp
aviiciii/iitb-exercises
e078e28fceb87eecc747272abd410e7279b22a97
[ "MIT" ]
null
null
null
week2/man_dog.cpp
aviiciii/iitb-exercises
e078e28fceb87eecc747272abd410e7279b22a97
[ "MIT" ]
null
null
null
#include <simplecpp> main_program { initCanvas("Man and Dog", 700, 700); //draw axes Turtle t; t.right(90); t.forward(350); t.right(180); t.forward(700); t.right(180); t.forward(350); t.right(90); t.forward(350); t.right(180); t.forward(750); Text tx1(400,365,"50"); Text tx2(450,365,"100"); Text tx3(500,365,"150"); Text tx4(550,365,"200"); Text tx5(600,365,"250"); Text tx6(650,365,"300"); wait(4); Turtle t1, t2; t1.setColor(COLOR("blue")); t2.setColor(COLOR("red")); t2.forward(300); t2.right(180); wait(4); repeat(50){ t1.forward(3); t2.forward(6); } wait(5); }
17.547619
41
0.506106
aviiciii
6ea88e63a74886932f19c68bba323ffcf6270374
1,497
hpp
C++
include/d_log_wrapper.hpp
domenn/cppcommonutil
8f8f071a274a57e4d1bcf7f09935a08175c1204e
[ "Unlicense" ]
null
null
null
include/d_log_wrapper.hpp
domenn/cppcommonutil
8f8f071a274a57e4d1bcf7f09935a08175c1204e
[ "Unlicense" ]
null
null
null
include/d_log_wrapper.hpp
domenn/cppcommonutil
8f8f071a274a57e4d1bcf7f09935a08175c1204e
[ "Unlicense" ]
null
null
null
#pragma once #ifdef D_USING_SPDLOG #include <d_spdlog/spd_logging.hpp> // Map level names ... #ifdef TRACE #define VERBOSE TRACE #endif #define WARNING WARN #define WARNING WARN #define D_ANY_LOG_DEFAULT_IMPL(level, ...) SPDLOG_##level(__VA_ARGS__) #define D_LOG_DEFAULT(level, ...) D_ANY_LOG_DEFAULT_IMPL(level, __VA_ARGS__) #define D_LOG(level, namestr, ...) SPDLOG_LOGGER_##level(spdl::get(namestr), __VA_ARGS__) #define D_LOGT(namestr, ...) SPDLOG_LOGGER_TRACE(spdl::get(namestr), __VA_ARGS__) #define D_LOGD(namestr, ...) SPDLOG_LOGGER_DEBUG(spdl::get(namestr), __VA_ARGS__) #define D_LOGI(namestr, ...) SPDLOG_LOGGER_INFO(spdl::get(namestr), __VA_ARGS__) #define D_LOGW(namestr, ...) SPDLOG_LOGGER_WARN(spdl::get(namestr), __VA_ARGS__) #define D_LOGE(namestr, ...) SPDLOG_LOGGER_ERROR(spdl::get(namestr), __VA_ARGS__) #define D_LOGF(namestr, ...) SPDLOG_LOGGER_CRITICAL(spdl::get(namestr), __VA_ARGS__) #define D_DLOGT(...) SPDLOG_TRACE(__VA_ARGS__) #define D_DLOGD(...) SPDLOG_DEBUG(__VA_ARGS__) #define D_DLOGI(...) SPDLOG_INFO(__VA_ARGS__) #define D_DLOGW(...) SPDLOG_WARN(__VA_ARGS__) #define D_DLOGE(...) SPDLOG_ERROR(__VA_ARGS__) #define D_DLOGF(...) SPDLOG_CRITICAL(__VA_ARGS__) #elif defined(D_USING_PLOG) // NOTE: Untested. Probably doesn't work. #define D_LOG_DEFAULT(level, ...) PLOG_##level << fmt::format(__VA_ARGS__); #define D_LOG(level, namestr, ...) PLOG_##level << namestr ": " << fmt::format(__VA_ARGS__); #else #define D_LOG(...) #define D_LOG_DEFAULT(...) #endif
37.425
92
0.751503
domenn
6eafdf3962cc7ba4f332c235594b6d890a07ce85
51,637
hpp
C++
Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
22
2019-09-07T22:38:01.000Z
2022-01-31T21:35:55.000Z
Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
null
null
null
Tools/RegistersGenerator/STM32F303/FieldValues/dma2fieldvalues.hpp
snorkysnark/CortexLib
0db035332ebdfbebf21ca36e5e04b78a5a908a49
[ "MIT" ]
9
2019-09-22T11:26:24.000Z
2022-03-21T10:53:15.000Z
/******************************************************************************* * Filename : dma2fieldvalues.hpp * * Details : Enumerations related with DMA2 peripheral. This header file is * auto-generated for STM32F303 device. * * *******************************************************************************/ #if !defined(DMA2ENUMS_HPP) #define DMA2ENUMS_HPP #include "fieldvalue.hpp" //for FieldValues template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_GIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_GIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_GIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TCIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TCIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TCIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_HTIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_HTIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_HTIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_ISR_TEIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_ISR_TEIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_ISR_TEIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF1_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF1_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF1_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF2_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF2_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF2_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF3_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF3_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF3_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF4_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF4_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF4_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF5_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF5_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF5_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF6_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF6_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF6_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CGIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CGIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CGIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTCIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTCIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTCIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CHTIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CHTIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CHTIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_IFCR_CTEIF7_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_IFCR_CTEIF7_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_IFCR_CTEIF7_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR1_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR1_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR1_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR1_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR1_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR1_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR1_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR1_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR1_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR2_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR2_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR2_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR2_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR2_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR2_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR2_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR2_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR2_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR3_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR3_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR3_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR3_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR3_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR3_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR3_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR3_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR3_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR4_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR4_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR4_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR4_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR4_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR4_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR4_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR4_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR4_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR5_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR5_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR5_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR5_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR5_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR5_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR5_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR5_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR5_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR6_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR6_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR6_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR6_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR6_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR6_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR6_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR6_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR6_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_EN_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_EN_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_EN_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_TCIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_TCIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_TCIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_HTIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_HTIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_HTIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_TEIE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_TEIE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_TEIE_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_DIR_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_DIR_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_DIR_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_CIRC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_CIRC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_CIRC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_PINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_PINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_PINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_MINC_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_MINC_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_MINC_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_PSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR7_PSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_MSIZE_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR7_MSIZE_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_PL_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 1U> ; using Value2 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 2U> ; using Value3 = FieldValue<DMA2_CCR7_PL_Values, BaseType, 3U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CCR7_MEM2MEM_Values: public RegisterField<Reg, offset, size, AccessMode> { using Value0 = FieldValue<DMA2_CCR7_MEM2MEM_Values, BaseType, 0U> ; using Value1 = FieldValue<DMA2_CCR7_MEM2MEM_Values, BaseType, 1U> ; } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CNDTR7_NDT_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CPAR7_PA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; template <typename Reg, size_t offset, size_t size, typename AccessMode, typename BaseType> struct DMA2_CMAR7_MA_Values: public RegisterField<Reg, offset, size, AccessMode> { } ; #endif //#if !defined(DMA2ENUMS_HPP)
45.176728
92
0.77979
snorkysnark
6eb8e526605af71564eb43da9d58f483a10d949e
636
cpp
C++
practice2/client.cpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
47
2016-05-20T08:49:47.000Z
2022-01-03T01:17:07.000Z
practice2/client.cpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
null
null
null
practice2/client.cpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
37
2016-07-25T04:52:08.000Z
2022-02-14T03:55:08.000Z
// Copyright (c) 2016 // Author: Chrono Law #include <std.hpp> //using namespace std; using std::cout; using std::endl; using std::vector; using std::string; #include <boost/asio.hpp> using namespace boost; using namespace boost::asio; int main() { cout << "client start" << endl; io_service ios; ip::tcp::socket sock(ios); ip::tcp::endpoint ep( ip::address::from_string("127.0.0.1"), 6677); sock.connect(ep); string str("hello world"); sock.write_some(buffer(str)); vector<char> v(100, 0); size_t n = sock.read_some(buffer(v)); cout << "recv "<< n << " :" << v.data() << endl; };
19.272727
53
0.611635
MaxHonggg
6eba7e03dfbf14404f71672278184027b9ddb131
1,214
cpp
C++
1_two_sum/1_two_sum.cpp
ttiimm2214/leetcode
489c76bf374e2116bcac6ece5efe901db62a5ce1
[ "MIT" ]
null
null
null
1_two_sum/1_two_sum.cpp
ttiimm2214/leetcode
489c76bf374e2116bcac6ece5efe901db62a5ce1
[ "MIT" ]
null
null
null
1_two_sum/1_two_sum.cpp
ttiimm2214/leetcode
489c76bf374e2116bcac6ece5efe901db62a5ce1
[ "MIT" ]
null
null
null
/* * Leetcode 1 Two Sum * * Compile: g++ 1_two_sum.cpp -o result * Execute: ./result */ // Given an array of integers, return indices of the two numbers such that they add up to a specific target. //You may assume that each input would have exactly one solution, and you may not use the same element twice. //Example: //Given nums = [2, 7, 11, 15], target = 9, //Because nums[0] + nums[1] = 2 + 7 = 9, //return [0, 1]. #include <iostream> #include <vector> #include <unordered_map> using namespace std; int main(){ //test case num = [2, 7, 11, 15] target = 9 vector<int> result; vector<int> nums; unordered_map<int,int> mapping; int TARGET = 9; int remain; nums.push_back(2); nums.push_back(7); nums.push_back(11); nums.push_back(15); int SIZE = nums.size(); // solution for (int i = 0; i < nums.size(); i++){ mapping[nums[i]]= i; } for(int i = 0; i < nums.size(); i++){ remain = TARGET - nums [i]; if (mapping.find(remain)!=mapping.end()&& mapping[remain] != i){ result.push_back(i); result.push_back(mapping[remain]); break; } } // output for leetcode // return result; // output for (int i = 0; i < result.size(); i++){ cout<< result [i]<< endl; } }
19.901639
109
0.62603
ttiimm2214
6ec404498eb171bc328a030cf8df021cae51df05
8,477
cpp
C++
src/Texture.cpp
Derjik/VaubanEngine
19792aeb7fe838c6b85d00270d15a2805f6fb9d5
[ "0BSD" ]
2
2018-10-09T14:31:12.000Z
2018-10-26T08:47:59.000Z
src/Texture.cpp
Derjik/VaubanEngine
19792aeb7fe838c6b85d00270d15a2805f6fb9d5
[ "0BSD" ]
null
null
null
src/Texture.cpp
Derjik/VaubanEngine
19792aeb7fe838c6b85d00270d15a2805f6fb9d5
[ "0BSD" ]
null
null
null
#include <SDL2/SDL_render.h> #include <VBN/Surface.hpp> #include <VBN/Texture.hpp> #include <VBN/Logging.hpp> #include <VBN/Exceptions.hpp> /*! * The main constructor for this class is private, external callers should use * the "from...()" factories instead. * * @param rawTexture SDL_Texture raw pointer to encapsulate in the internal * std::unique_ptr (assuming ownership) * @throws Exception nullptr passed for rawTexture parameter */ Texture::Texture(SDL_Texture * rawTexture) : _rawTexture(rawTexture, &SDL_DestroyTexture), _pixelFormat(0), _access(0), _width(0), _height(0) { // Check input parameters if(rawTexture == nullptr) THROW(Exception, "Received nullptr 'rawTexture'"); // Acquire SDL_Texture metrics SDL_QueryTexture( _rawTexture.get(), &_pixelFormat, &_access, &_width, &_height); // Add a special, "global" clip matching the whole surface _clips.emplace("", SDL_Rect{ 0, 0, _width, _height }); // Log VERBOSE(SDL_LOG_CATEGORY_APPLICATION, "Build Texture %p (SDL_Texture %p)", this, _rawTexture.get()); } Texture::Texture(Texture && other) : _rawTexture(std::move(other._rawTexture)), _clips(std::move(other._clips)), _pixelFormat(std::move(other._pixelFormat)), _access(std::move(other._access)), _width(std::move(other._width)), _height(std::move(other._height)) { VERBOSE(SDL_LOG_CATEGORY_APPLICATION, "Move Texture %p (SDL_Texture %p) into new Texture %p", &other, _rawTexture.get(), this); } Texture & Texture::operator=(Texture && other) { //! @todo Leak check below this->_rawTexture = std::move(other._rawTexture); this->_clips = std::move(other._clips); this->_pixelFormat = std::move(other._pixelFormat); this->_access = std::move(other._access); this->_width = std::move(other._width); this->_height = std::move(other._height); VERBOSE(SDL_LOG_CATEGORY_APPLICATION, "Move (assign) Texture %p (SDL_Texture %p) into Texture %p", &other, _rawTexture.get(), this); return (*this); } Texture::~Texture(void) { VERBOSE(SDL_LOG_CATEGORY_APPLICATION, "Delete Texture %p (SDL_Texture %p)", this, _rawTexture.get()); } SDL_Texture * Texture::getSDLTexture(void) { return _rawTexture.get(); } int Texture::getWidth(void) const { return _width; } int Texture::getHeight(void) const { return _height; } int Texture::getAccess(void) const { return _access; } Uint32 Texture::getPixelFormat(void) const { return _pixelFormat; } void Texture::setColorAlphaMod(SDL_Color const & color) { if(SDL_SetTextureColorMod(_rawTexture.get(), color.r, color.g, color.b)) ERROR(SDL_LOG_CATEGORY_ERROR, "Failed to set color and alpha : SDL error '%s'", SDL_GetError()); } SDL_Color Texture::getColorAlphaMod(void) const { SDL_Color rgba{0,0,0,0}; if(SDL_GetTextureColorMod(_rawTexture.get(), &rgba.r, &rgba.g, &rgba.b)) ERROR(SDL_LOG_CATEGORY_ERROR, "Failed to get color mod : SDL erorr '%s'", SDL_GetError()); if(SDL_GetTextureAlphaMod(_rawTexture.get(), &rgba.a)) ERROR(SDL_LOG_CATEGORY_ERROR, "Failed to get alpha mod : SDL error '%s'", SDL_GetError()); return rgba; } /*! * @param ttfManager Shared reference on a valid TrueTypeFontManager from * which to extract the TrueTypeFont to use * @param renderer Raw pointer to the SDL_Renderer to use * @param text Latin1-encoded string to print * @param textFontName Font name * @param textSize Font size * @param textColor Font color * @returns A newly created Texture instance containing the * text render * @throws Exception Invalid input parameters, Surface instantiation * or conversion error */ Texture Texture::fromLatin1Text( std::shared_ptr<TrueTypeFontManager> ttfManager, SDL_Renderer * renderer, std::string const & text, std::string const & textFontName, int const textSize, SDL_Color const & textColor) { // Check input parameters if (!ttfManager) THROW(Exception, "Received nullptr 'ttfManager'"); if (renderer == nullptr) THROW(Exception, "Received nullptr 'renderer'"); if (textFontName.empty()) THROW(Exception, "Received empty 'textFontName'"); if (textSize <= 0) THROW(Exception, "Received textSize <= 0"); // Instantiate Text Surface Surface textSurface( Surface::fromLatin1Text( ttfManager, text, textFontName, textSize, textColor)); // Attempt conversion to Texture return Texture::fromSurface(renderer, textSurface); } /*! * @param ttfManager Shared reference on a valid TrueTypeFontManager from * which to extract the TrueTypeFont to use * @param renderer Raw pointer to the SDL_Renderer to use * @param text UTF-8-encoded string to print * @param textFontName Font name * @param textSize Font size * @param textColor Font color * @returns A newly created Texture instance containing the * text render * @throws Exception Invalid input parameters, Surface instantiation * or conversion error */ Texture Texture::fromUTF8Text( std::shared_ptr<TrueTypeFontManager> ttfManager, SDL_Renderer * renderer, std::string const & text, std::string const & textFontName, int const textSize, SDL_Color const & textColor) { // Check input parameters if (!ttfManager) THROW(Exception, "Received nullptr 'ttfManager'"); if (renderer == nullptr) THROW(Exception, "Received nullptr 'renderer'"); if (textFontName.empty()) THROW(Exception, "Received empty 'textFontName'"); if (textSize <= 0) THROW(Exception, "Received textSize <= 0"); // Instantiate Text Surface Surface textSurface( Surface::fromUTF8Text( ttfManager, text, textFontName, textSize, textColor)); // Attempt conversion to Texture return Texture::fromSurface(renderer, textSurface); } /*! * @param renderer Raw pointer to the SDL_Renderer to use * @param surface Reference to the Surface instance to convert * @returns A newly created Texture built from the input Surface * contents * @throws Exception Invalid input parameters or SDL_Surface to SDL_Texture * conversion error */ Texture Texture::fromSurface( SDL_Renderer * renderer, Surface & surface) { // Check input parameters if (renderer == nullptr) THROW(Exception, "Received nullptr 'renderer'"); // Attempt SDL_Surface to SDL_Texture conversion SDL_Texture * rawTexture = SDL_CreateTextureFromSurface(renderer, surface.getSurface()); // Check for failure if (rawTexture == nullptr) THROW(Exception, "Cannot instantiate SDL_Texture : SDL error '%s'", SDL_GetError()); // Return encapsulated Texture return Texture(rawTexture); } /*! * @param renderer Raw pointer to the SDL_Renderer to use * @param format Pixel format * @param access Access mode * @param width Width * @param height Height * @returns A blank Texture created from input parameters * @throws Invalid input parameters or SDL error */ Texture Texture::fromScratch( SDL_Renderer * renderer, Uint32 const format, int const access, int const width, int const height) { // Check input parameters if (renderer == nullptr) THROW(Exception, "Received nullptr 'renderer'"); if (width <= 0) THROW(Exception, "Received 'width' <= 0"); if (height <= 0) THROW(Exception, "Received 'height' <= 0"); // Attempt SDL_Texture creation from scratch SDL_Texture * rawTexture = SDL_CreateTexture( renderer, format, access, width, height); // Check for failure if(rawTexture == nullptr) THROW(Exception, "Cannot instantiate SDL_Texture : SDL error '%s'", SDL_GetError()); // Return encapsulated Texture return Texture(rawTexture); } /*! * @param name Human-readable name to associate with the clipping * rectangle * @param clip SDL_Rect representing the clipping area * @throws Exception Invalid input parameters */ void Texture::addClip( std::string const & name, SDL_Rect const & clip) { // Check input parameters if (name.empty()) THROW(Exception, "Received empty 'name'"); if(_clips.find(name) != _clips.end()) THROW(Exception, "Cannot override existing clip '%s'", name); // Store _clips.emplace(name, clip); } /*! * @param name Human-readable name of the wanted clip * @returns Raw pointer to the SDL_Rect clip if it exists, nullptr * otherwise */ SDL_Rect * Texture::getClip(std::string const & name) { // Clip lookup auto clipIterator = _clips.find(name); if (clipIterator == _clips.end()) /* Miss */ return nullptr; else return (&clipIterator->second); /* Hit */ }
25.079882
78
0.712634
Derjik
6ec447129489d64b92aeb18f535e9c5e18325ffa
7,132
cpp
C++
kernel/process/thread.cpp
USN484259/COFUOS
a751c3ab1a24f634ae33b5ddced55c184c8f9381
[ "MIT" ]
1
2022-03-03T09:57:56.000Z
2022-03-03T09:57:56.000Z
kernel/process/thread.cpp
USN484259/COFUOS
a751c3ab1a24f634ae33b5ddced55c184c8f9381
[ "MIT" ]
null
null
null
kernel/process/thread.cpp
USN484259/COFUOS
a751c3ab1a24f634ae33b5ddced55c184c8f9381
[ "MIT" ]
1
2022-01-22T14:19:24.000Z
2022-01-22T14:19:24.000Z
#include "thread.hpp" #include "core_state.hpp" #include "constant.hpp" #include "memory/include/vm.hpp" #include "process.hpp" #include "pe64.hpp" #include "dev/include/timer.hpp" #include "lock_guard.hpp" #include "assert.hpp" using namespace UOS; id_gen<dword> thread::new_id; //initial thread thread::thread(initial_thread_tag, process* p) : id(new_id()), state(RUNNING), critical(0), priority(scheduler::kernel_priority), slice(scheduler::max_slice), ps(p) { assert(ps && id == 0); krnl_stk_top = 0; //??? krnl_stk_reserved = pe_kernel->stk_reserve; } thread::thread(process* p, procedure entry, const qword* args, qword stk_size) : id(new_id()), state(READY), critical(0), priority(this_core().this_thread()->get_priority()), slice(scheduler::max_slice), ps(p), krnl_stk_reserved(align_down(stk_size,PAGE_SIZE)) { IF_assert; assert(ps && krnl_stk_reserved >= PAGE_SIZE); lock_guard<spin_lock> guard(objlock); auto va = vm.reserve(0,2 + krnl_stk_reserved/PAGE_SIZE); if (!va) bugcheck("vm.reserve failed with 0x%x pages",krnl_stk_reserved); krnl_stk_top = va + PAGE_SIZE + krnl_stk_reserved; auto res = vm.commit(krnl_stk_top - PAGE_SIZE,1); if (!res) bugcheck("vm.commit failed @ %p",krnl_stk_top - PAGE_SIZE); gpr.rbp = krnl_stk_top; gpr.rsp = krnl_stk_top - 0x30; gpr.ss = SEG_KRNL_SS; gpr.cs = SEG_KRNL_CS; gpr.rip = reinterpret_cast<qword>(entry); gpr.rflags = 0x202; //IF gpr.rcx = args[0]; gpr.rdx = args[1]; gpr.r8 = args[2]; gpr.r9 = args[3]; #ifdef PS_TEST dbgprint("new thread $%d @ %p",id,this); #endif ready_queue.put(this); } thread::~thread(void){ if (state != STOPPED) bugcheck("deleting non-stop thread #%d @ %p",id,this); // if (hold_lock) // bugcheck("deleting thread #%d @ %p while holding lock %x",id,this,hold_lock); #ifdef PS_TEST dbgprint("deleted thread #%d @ %p",id,this); #endif if (sse){ //flush FPU state from this core this_core core; if (core.fpu_owner() == this){ core.fpu_owner(nullptr); } //TODO remove FPU context from all processor core delete sse; } if (user_stk_top){ // if (!get_process()->vspace->release(user_stk_top - user_stk_reserved - PAGE_SIZE,1 + user_stk_reserved/PAGE_SIZE)) // bugcheck("vspace->release failed @ %p",user_stk_top - user_stk_reserved); get_process()->vspace->release(user_stk_top - user_stk_reserved - PAGE_SIZE,1 + user_stk_reserved/PAGE_SIZE); } if (!vm.release(krnl_stk_top - krnl_stk_reserved - PAGE_SIZE,2 + krnl_stk_reserved/PAGE_SIZE)) bugcheck("vm.release failed @ %p",krnl_stk_top - krnl_stk_reserved); } REASON thread::wait(qword us,wait_callback func){ if (state == STOPPED){ if (func){ func(); } return PASSED; } return waitable::wait(us,func); } bool thread::set_priority(byte val){ if (val >= scheduler::max_priority) return false; priority = val; return true; } bool thread::set_state(thread::STATE st, qword arg, waitable* obj){ IF_assert; assert(objlock.is_locked()); if (state == STOPPED){ return false; } switch(st){ case READY: if (state == WAITING){ //arg as reason switch(arg){ case REASON::ABANDON: assert(wait_for); wait_for->cancel(this); //fall through case REASON::NOTIFY: assert(wait_for); if (timer_ticket) timer.cancel(timer_ticket); break; case REASON::TIMEOUT: assert(timer_ticket); if (wait_for) wait_for->cancel(this); break; default: assert(false); } reason = (REASON)arg; wait_for = nullptr; timer_ticket = 0; } break; case RUNNING: assert(state == READY); break; case WAITING: assert(state == RUNNING); //arg as timer_ticket, obj as wait_for assert(arg || obj); assert(wait_for == nullptr && timer_ticket == 0); wait_for = obj; timer_ticket = arg; break; default: bugcheck("thread::set_state bad state @ %p",this); } state = st; return true; } bool thread::relax(void){ interrupt_guard<void> ig; auto res = waitable::relax(); if (!res){ ps->erase(this); } return res; } void thread::manage(void*){ IF_assert; waitable::manage(); ++ref_count; assert(ref_count == 2); } void thread::on_stop(void){ IF_assert; assert(objlock.is_locked()); assert(state == thread::STOPPED); assert(wait_for == nullptr && timer_ticket == 0); /* if (hold_lock){ if (hold_lock & HOLD_VSPACE){ auto vspace = get_process()->vspace; assert(vspace->is_locked() && !vspace->is_exclusive()); vspace->unlock(); } if (hold_lock & HOLD_HANDLE){ auto& ht = get_process()->handles; assert(ht.is_locked() && !ht.is_exclusive()); ht.unlock(); } hold_lock = 0; } */ gc.put(this); objlock.unlock(); } void thread::on_gc(void){ interrupt_guard<spin_lock> guard(objlock); guard.drop(); notify(); ps->on_exit(); relax(); } void thread::save_sse(void){ if (!sse){ sse = new SSE_context; } assert((qword)sse == align_down((qword)sse, sizeof(sse))); fxsave(sse); } void thread::load_sse(void){ if (sse){ fxrstor(sse); } else{ fpu_init(); } } void thread::hold(void){ interrupt_guard<spin_lock> guard(objlock); assert(critical == 0); critical = CRITICAL; } void thread::drop(void){ { interrupt_guard<spin_lock> guard(objlock); assert(critical & CRITICAL); critical &= ~CRITICAL; if (0 == (critical & KILL)) return; assert(state == RUNNING); state = STOPPED; } interrupt_guard<void> ig; core_manager::preempt(true); bugcheck("failed to escape @ %p",this); } void thread::sleep(qword us){ this_core core; thread* this_thread = core.this_thread(); interrupt_guard<void> ig; if (this_thread->has_context()) bugcheck("sleep called in IRQ @ %p",this_thread); if (us == 0){ this_thread->put_slice(scheduler::max_slice); core_manager::preempt(true); return; } thread* next_thread; bool need_gc = false; do{ next_thread = ready_queue.get(); if (!next_thread) bugcheck("no ready thread"); next_thread->lock(); if (next_thread->set_state(thread::RUNNING)) break; next_thread->on_stop(); need_gc = true; }while(true); if (need_gc) gc.signal(); this_thread->lock(); auto ticket = timer.wait(us,on_timer,this_thread); if (!this_thread->set_state(thread::WAITING,ticket,nullptr)){ timer.cancel(ticket); } this_thread->unlock(); core.switch_to(next_thread); } void thread::kill(thread* th){ #ifdef PS_TEST dbgprint("killing thread %d @ %p",th->id,th); #endif this_core core; thread* this_thread = core.this_thread(); bool kill_self = (this_thread == th); interrupt_guard<void> ig; { lock_guard<thread> guard(*th); if (th->critical & CRITICAL){ assert(this_thread != th); th->critical |= KILL; return; } //th->set_state(STOPPED); auto state = th->state; th->state = STOPPED; assert(!kill_self || state == RUNNING); if (state == WAITING){ if (th->wait_for){ th->wait_for->cancel(th); th->wait_for = nullptr; } if (th->timer_ticket){ timer.cancel(th->timer_ticket); th->timer_ticket = 0; } if (!kill_self){ guard.drop(); th->on_stop(); gc.signal(); } } } if (kill_self){ core_manager::preempt(true); bugcheck("failed to escape @ %p",th); } }
23.23127
262
0.671761
USN484259
6ec5ebf72f798a370e0143c6238fdf7759f09726
1,346
cpp
C++
src/test_distribution.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
src/test_distribution.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
src/test_distribution.cpp
inesc-tec-robotics/carlos_controller
ffcc45f24dd534bb953d5bd4a47badd3d3d5223d
[ "BSD-3-Clause" ]
null
null
null
#include <mission_ctrl_msgs/generateStudDistributionAction.h> #include <mission_ctrl_msgs/mission_ctrl_defines.h> #include <actionlib/client/simple_action_client.h> typedef actionlib::SimpleActionClient<mission_ctrl_msgs::generateStudDistributionAction> Client; void finishedHnd(const actionlib::SimpleClientGoalState& state, const mission_ctrl_msgs::generateStudDistributionResultConstPtr& result) { fprintf(stdout, "Action finished in state %s\n", state.toString().c_str()); fprintf(stdout, "Error: %s\n", result->error_string.c_str()); for(int i=0; i<result->positions.size(); i++){ fprintf(stdout, "/tasks/test_task/studs/stud_%d/x: %f\n", i+1, result->positions[i].x); fprintf(stdout, "/tasks/test_task/studs/stud_%d/y: %f\n", i+1, result->positions[i].y); } ros::shutdown(); } void activeHnd() { fprintf(stdout, "Goal active\n"); } void feedbackHnd(const mission_ctrl_msgs::generateStudDistributionFeedbackConstPtr& feedback) { fprintf(stdout, "Feedback executed\n"); } int main(int argc, char** argv) { ros::init(argc, argv, "test_generate_distribution"); Client client(CARLOS_DISTRIBUTION_ACTION, true); client.waitForServer(); mission_ctrl_msgs::generateStudDistributionGoal goal; goal.side = 1; client.sendGoal(goal, &finishedHnd, &activeHnd, &feedbackHnd); ros::spin(); return 0; }
28.638298
96
0.746657
inesc-tec-robotics
6ecad6eb9fe81c9b4f19eb409116b3f286fb4bd7
1,062
cpp
C++
PlayerData.cpp
GracefulComet/Graceful-Engine
cc3e4dd6da0a13904d062ebbc21c198c8b42aac6
[ "MIT" ]
null
null
null
PlayerData.cpp
GracefulComet/Graceful-Engine
cc3e4dd6da0a13904d062ebbc21c198c8b42aac6
[ "MIT" ]
null
null
null
PlayerData.cpp
GracefulComet/Graceful-Engine
cc3e4dd6da0a13904d062ebbc21c198c8b42aac6
[ "MIT" ]
null
null
null
#include "PlayerData.h" PlayerMSG::PlayerMSG(PlayerAction action, ID target, ID sender ) :msg(target,sender,MSGTYPE::Player) { m_action = action; } void PlayerMSG::update(void* Variables){ auto &mybod = *reinterpret_cast<b2Body*>(Variables); switch( m_action){ case PlayerAction::Idle: break; case PlayerAction::WalkLeft : mybod.ApplyLinearImpulse( b2Vec2(-500,0), mybod.GetWorldCenter(), true); mybod.ApplyForce( b2Vec2(-500000,0), mybod.GetWorldCenter(), true); break; case PlayerAction::WalkRight: mybod.ApplyLinearImpulse( b2Vec2(500 ,0), mybod.GetWorldCenter(), true); mybod.ApplyForce( b2Vec2(500000, 0), mybod.GetWorldCenter(), true); break; case PlayerAction::Jump: mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true); mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true); mybod.ApplyLinearImpulse( b2Vec2(0,-50000), mybod.GetWorldCenter(), true); break; case PlayerAction::Crouch: break; case PlayerAction::SlowToStop: break; default : break; } }
22.125
76
0.720339
GracefulComet
6ecae98fe9c4d2ee70fbbef1b6186b1fc18708bb
5,758
cpp
C++
src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp
MichaelTiernan/qvge
aff978d8592e07e24af4b8bab7c3204a7e7fb3fb
[ "MIT" ]
3
2021-09-14T08:11:37.000Z
2022-03-04T15:42:07.000Z
src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp
MichaelTiernan/qvge
aff978d8592e07e24af4b8bab7c3204a7e7fb3fb
[ "MIT" ]
2
2021-12-04T17:09:53.000Z
2021-12-16T08:57:25.000Z
src/3rdParty/ogdf-2020/src/ogdf/basic/graph_generators/deterministic.cpp
MichaelTiernan/qvge
aff978d8592e07e24af4b8bab7c3204a7e7fb3fb
[ "MIT" ]
2
2021-06-22T08:21:54.000Z
2021-07-07T06:57:22.000Z
/** \file * \brief Implementation of some graph generators * * \author Carsten Gutwenger, Markus Chimani * * \par License: * This file is part of the Open Graph Drawing Framework (OGDF). * * \par * Copyright (C)<br> * See README.md in the OGDF root directory for details. * * \par * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 or 3 as published by the Free Software Foundation; * see the file LICENSE.txt included in the packaging of this file * for details. * * \par * 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. * * \par * You should have received a copy of the GNU General Public * License along with this program; if not, see * http://www.gnu.org/copyleft/gpl.html */ #include <ogdf/basic/graph_generators/deterministic.h> #include <ogdf/basic/simple_graph_alg.h> #include <ogdf/basic/CombinatorialEmbedding.h> #include <ogdf/basic/FaceArray.h> #include <ogdf/basic/extended_graph_alg.h> #include <ogdf/basic/Array2D.h> #include <ogdf/basic/geometry.h> #include <ogdf/basic/Math.h> #include <ogdf/planarity/PlanarizationGridLayout.h> #include <ogdf/planarlayout/SchnyderLayout.h> using std::minstd_rand; using std::uniform_int_distribution; using std::uniform_real_distribution; namespace ogdf { void customGraph(Graph &G, int n, List<std::pair<int,int>> edges, Array<node> &nodes) { nodes.init(n); G.clear(); for (int i = 0; i < n; i++) { nodes[i] = G.newNode(); } for (auto e : edges) { G.newEdge(nodes[std::get<0>(e)], nodes[std::get<1>(e)]); } } void circulantGraph(Graph &G, int n, Array<int> jumps) { G.clear(); Array<node> nodes(n); for (int i=0; i<n; i++) { nodes[i] = G.newNode(); } Array2D<bool> buildEdge(0,n-1,0,n-1,false); auto pos_modulo = [&n](int i) {return (i % n + n) % n;}; for (int s: jumps) { for (int i=0; i<n; i++) { buildEdge(i, pos_modulo(i+s)) = true; buildEdge(i, pos_modulo(i-s)) = true; } } for (int i=0; i<n; i++) { for (int j=i; j<n; j++) { if (buildEdge(i,j)) { G.newEdge(nodes[i], nodes[j]); } } } } void regularTree(Graph& G, int n, int children) { G.clear(); node* id2node = new node[n]; id2node[0] = G.newNode(); for(int i=1; i<n; i++) { G.newEdge(id2node[(i-1)/children], id2node[i] = G.newNode()); } delete[] id2node; } void completeGraph(Graph &G, int n) { G.clear(); Array<node> v(n); int i,j; for(i = n; i-- > 0;) v[i] = G.newNode(); for(i = n; i-- > 0;) for(j = i; j-- > 0;) G.newEdge(v[i],v[j]); } void completeKPartiteGraph(Graph &G, const Array<int> &signature) { G.clear(); if (signature.size() <= 0) { return; } Array<Array<node>> partitions(signature.size()); // generate nodes in partitions for (int i = 0; i < partitions.size(); ++i) { OGDF_ASSERT(signature[i] > 0); partitions[i].init(signature[i]); for (int j = 0; j < signature[i]; ++j) { partitions[i][j] = G.newNode(); } } // generate edges for (int i = 0; i < partitions.size(); ++i) { for (node u : partitions[i]) { for (int j = i+1; j < partitions.size(); ++j) { for (node v : partitions[j]) { G.newEdge(u, v); } } } } } void completeBipartiteGraph(Graph &G, int n, int m) { completeKPartiteGraph(G, {n, m}); } void wheelGraph(Graph &G, int n) { G.clear(); if (n <= 2) return; node center = G.newNode(); node n0 = nullptr; node n1 = nullptr; while (n--) { node n2 = G.newNode(); G.newEdge(center, n2); if (n1) G.newEdge(n1, n2); else n0 = n2; n1 = n2; } G.newEdge(n1, n0); } void suspension(Graph &G, int n) { if(n == 0) return; OGDF_ASSERT( n>0 ); List<node> nds; G.allNodes(nds); while (n--) { node n0 = G.newNode(); for(node v : nds) G.newEdge(n0,v); } } void cubeGraph(Graph &G, int n) { OGDF_ASSERT(n >= 0); OGDF_ASSERT(n < 8*(int)sizeof(int)-1); // one sign bit, one less to be safe G.clear(); int c = 1 << n; Array<node> lu(c); for(int i=0; i<c; ++i) { lu[i] = G.newNode(); int q = 1; while( q <= i ) { if(q&i) G.newEdge(lu[i^q],lu[i]); q <<= 1; } } } void gridGraph(Graph &G, int n, int m, bool loopN, bool loopM) { G.clear(); Array<node> front(0,n-1,nullptr); Array<node> fringe(0,n-1,nullptr); node first = nullptr; node last = nullptr; node cur; for(int j = m; j-- > 0;) { for(int i = n; i-- > 0;) { cur = G.newNode(); if(!last) first=cur; else G.newEdge(last,cur); if(fringe[i]) G.newEdge(fringe[i],cur); else front[i] = cur; fringe[i] = cur; last = cur; } if(loopN) G.newEdge(last, first); last = nullptr; } if(loopM) { for(int i = n; i-- > 0;) { G.newEdge(fringe[i],front[i]); } } } void petersenGraph(Graph &G, int n, int m) { G.clear(); Array<node> inner(0, n-1, nullptr); node first = nullptr; node last = nullptr; for(int i = n; i-- > 0;) { node outn = G.newNode(); node inn = G.newNode(); G.newEdge(outn,inn); inner[i]=inn; if(!last) first=outn; else G.newEdge(last,outn); last = outn; } G.newEdge(last, first); for(int i = n; i-- > 0;) { G.newEdge(inner[i],inner[(i+m)%n]); } } void regularLatticeGraph(Graph &G, int n, int k) { OGDF_ASSERT(n >= 4); // For a circle with all even degrees, we need at least four nodes. OGDF_ASSERT(k > 0); OGDF_ASSERT(k <= n-2); OGDF_ASSERT(k % 2 == 0); Array<int> jumps = Array<int>(k/2); for (int i = 0; i < k/2; i++) { jumps[i] = i+1; } circulantGraph(G, n, jumps); } void emptyGraph(Graph &G, int nodes) { G.clear(); for (int i = 0; i < nodes; i++) { G.newNode(); } } }
20.062718
89
0.609934
MichaelTiernan
6ed0caefcd0ab8aff75867a73e480389777cb7e1
1,095
hpp
C++
device-manager.hpp
KeyboxWallet/keyboxd
67c9103aaf48d5e83c922311acf5a4deab8c0755
[ "MIT" ]
2
2018-11-26T10:40:46.000Z
2019-05-30T05:30:01.000Z
device-manager.hpp
KeyboxWallet/keyboxd
67c9103aaf48d5e83c922311acf5a4deab8c0755
[ "MIT" ]
null
null
null
device-manager.hpp
KeyboxWallet/keyboxd
67c9103aaf48d5e83c922311acf5a4deab8c0755
[ "MIT" ]
1
2018-10-16T10:17:23.000Z
2018-10-16T10:17:23.000Z
#ifndef _KEYBOX_DEVICE_MANAGER_INCLUDE_ #define _KEYBOX_DEVICE_MANAGER_INCLUDE_ #include "base-device.hpp" #define KEYBOX2_VENDOR_ID 0xb6ab #define KEYBOX2_PRODUCT_ID 0xbaeb #define KEYBOX2_BCD_DEVICE 0x0001 #include <boost/asio.hpp> #include <set> class DeviceEventListener { public: virtual void deviceAdded(BaseDevice *) = 0; virtual void deviceRemoved(const std::string &dev_id) = 0; }; class DeviceManager { public: static DeviceManager * getDeviceManager(boost::asio::io_context *ioc); BaseDevice * getDeviceById(const std::string &id ); std::vector<BaseDevice*> deviceList(); void addDevice(BaseDevice *); void rmDevice(BaseDevice *); void registerEventListener(DeviceEventListener *listener); void unRegisterEventListener(DeviceEventListener *listener); private: boost::asio::io_context * mContext; explicit DeviceManager(boost::asio::io_context *ioc); std::map<std::string, BaseDevice *> mDeviceMaps; std::set<DeviceEventListener *> mListeners; boost::asio::steady_timer *mTimer; void enumerateUsbDevice(); }; #endif
27.375
74
0.750685
KeyboxWallet
6ed55ed03b8a725a0e8cfa7a7481e4645e53f254
109,294
cpp
C++
src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/nPaintingSecretGui.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
#include <exciton.h> /////////////////////////////////////////////////////////////////////////////// #define DEBUGPAINTING #ifdef DEBUGPAINTING #define XDEBUG(msg) if (plan->Verbose>=90) plan -> Debug ( msg) #else #define XDEBUG(msg) #endif /////////////////////////////////////////////////////////////////////////////// typedef struct { int Id ; char * Path ; } LocaleDirectory ; #pragma message("PaintingSecretGui LocaleDirectory requires some fix up") LocaleDirectory LocaleDirectories[4096] ; void * psLocaleDirectories = (void *)LocaleDirectories ; static bool LidTo(int Id,QString & LC) { int i = 0 ; while (LocaleDirectories[i].Id!=0) { if (Id==LocaleDirectories[i].Id) { LC = LocaleDirectories[i].Path ; return true ; } ; i++ ; } ; return false ; } N::PaintingSecretGui:: PaintingSecretGui ( QWidget * parent , Plan * p ) : Splitter ( Qt::Vertical , parent , p ) , header ( NULL ) , stack ( NULL ) , menu ( NULL ) , encrypt ( NULL ) , decrypt ( NULL ) , depot ( NULL ) , settings ( NULL ) , srcPicture ( NULL ) , keyPicture ( NULL ) , picTool ( NULL ) , fileTool ( NULL ) , folderTool ( NULL ) , folderEdit ( NULL ) , textTool ( NULL ) , audioTool ( NULL ) , folderList ( NULL ) , vcf ( NULL ) , ftp ( NULL ) , fontconf ( NULL ) , screenconf ( NULL ) , mdi ( NULL ) , label ( NULL ) , progress ( NULL ) , pickPicture ( NULL ) , pickLanguage ( NULL ) , encryptReport ( NULL ) , decryptReport ( NULL ) , plainText ( NULL ) , line ( NULL ) , archive ( NULL ) , pickArchive ( NULL ) , help ( NULL ) , packaging ( 0 ) , SourcePicture ( "" ) , KeyPicture ( "" ) , DecryptPicture ( "" ) , DecryptKey ( "" ) , BackWidget ( NULL ) , BackMenu ( NULL ) , ReturnLabel ( "" ) , debug ( false ) { Configure ( ) ; } N::PaintingSecretGui::~PaintingSecretGui (void) { } QSize N::PaintingSecretGui::sizeHint(void) const { if ( plan -> Booleans [ "Desktop" ] ) { return QSize ( 1280 , 900 ) ; } else if ( plan -> Booleans [ "Pad" ] ) { return QSize ( 1024 , 720 ) ; } else if ( plan -> Booleans [ "Phone" ] ) { return QSize ( 320 , 480 ) ; } ; return QSize ( 1024 , 720 ) ; } void N::PaintingSecretGui::resizeEvent(QResizeEvent * event) { QSplitter :: resizeEvent ( event ) ; relocation ( ) ; } void N::PaintingSecretGui::showEvent(QShowEvent * event) { QSplitter :: showEvent ( event ) ; relocation ( ) ; } void N::PaintingSecretGui::Configure (void) { setHandleWidth ( 1 ) ; //////////////////////////////////////////////////////// plan -> settings . beginGroup ( "System" ) ; if (plan->settings.contains("Debug")) { debug = plan->settings.value("Debug").toBool() ; } ; plan -> settings . endGroup ( ) ; //////////////////////////////////////////////////////// header = new StackedWidget ( this , plan ) ; stack = new StackedWidget ( this , plan ) ; menu = new StackedWidget ( this , plan ) ; //////////////////////////////////////////////////////// header -> setMinimumHeight ( 28 ) ; header -> setMaximumHeight ( 28 ) ; menu -> setMinimumHeight ( 40 ) ; menu -> setMaximumHeight ( 40 ) ; //////////////////////////////////////////////////////// addWidget ( header ) ; addWidget ( stack ) ; addWidget ( menu ) ; //////////////////////////////////////////////////////// encrypt = new PaintingEncryptionTool ( menu , plan ) ; decrypt = new PaintingDecryptionTool ( menu , plan ) ; depot = new PaintingDepotTool ( menu , plan ) ; settings = new PaintingSettingsTool ( menu , plan ) ; srcPicture = new PaintingPickTool ( menu , plan ) ; keyPicture = new PaintingPickTool ( menu , plan ) ; getEncrypt = new PaintingPickTool ( menu , plan ) ; getKeyPic = new PaintingPickTool ( menu , plan ) ; viewImages = new PaintingPickTool ( menu , plan ) ; viewEncrypt = new PaintingPickTool ( menu , plan ) ; viewKeys = new PaintingPickTool ( menu , plan ) ; fileTool = new PaintingFilesTool ( menu , plan ) ; folderTool = new PaintingFolderTool ( menu , plan ) ; textTool = new PaintingTextTool ( menu , plan ) ; textEdit = new PaintingTextTool ( menu , plan ) ; audioTool = new PaintingAudioTool ( menu , plan ) ; folderEdit = new PaintingFolderEdit ( menu , plan ) ; //////////////////////////////////////////////////////// menu -> addWidget ( encrypt ) ; menu -> addWidget ( decrypt ) ; menu -> addWidget ( depot ) ; menu -> addWidget ( settings ) ; menu -> addWidget ( srcPicture ) ; menu -> addWidget ( keyPicture ) ; menu -> addWidget ( getEncrypt ) ; menu -> addWidget ( getKeyPic ) ; menu -> addWidget ( viewImages ) ; menu -> addWidget ( viewEncrypt ) ; menu -> addWidget ( viewKeys ) ; menu -> addWidget ( fileTool ) ; menu -> addWidget ( folderTool ) ; menu -> addWidget ( textTool ) ; menu -> addWidget ( textEdit ) ; menu -> addWidget ( audioTool ) ; menu -> addWidget ( folderEdit ) ; //////////////////////////////////////////////////////// viewImages -> canPick = false ; viewEncrypt -> canPick = false ; viewKeys -> canPick = false ; //////////////////////////////////////////////////////// ftp = new FtpControl ( stack , plan ) ; stack -> addWidget ( ftp ) ; ftp -> startup ( ) ; ftp -> setBack ( false ) ; //////////////////////////////////////////////////////// label = new QLabel ( header ) ; header -> addWidget ( label ) ; label -> setStyleSheet ( "QLabel{background:rgb(255,255,255);}" ) ; //////////////////////////////////////////////////////// progress = new QProgressBar ( header ) ; header -> addWidget ( progress ) ; //////////////////////////////////////////////////////// folderList = new PaintingFolderList ( header ) ; header -> addWidget ( folderList ) ; //////////////////////////////////////////////////////// fontconf = new FontConfigurator ( stack , plan ) ; fontconf->addItem(Fonts::Default ,tr("Default" )) ; fontconf->addItem(Fonts::Menu ,tr("Menu" )) ; fontconf->addItem(Fonts::Status ,tr("Status" )) ; fontconf->addItem(Fonts::Message ,tr("Message" )) ; fontconf->addItem(Fonts::ComboBox ,tr("Drop items")) ; fontconf->addItem(Fonts::TreeView ,tr("Text items")) ; fontconf->addItem(Fonts::ListView ,tr("Icon text" )) ; fontconf->addItem(Fonts::TableView ,tr("Table" )) ; fontconf->addItem(Fonts::Label ,tr("Label" )) ; fontconf->addItem(Fonts::CheckBox ,tr("CheckBox" )) ; fontconf->addItem(Fonts::Progress ,tr("Progress" )) ; fontconf->addItem(Fonts::Button ,tr("Button" )) ; fontconf->addItem(Fonts::Spin ,tr("Spin" )) ; stack ->addWidget(fontconf) ; fontconf->startup() ; fontconf->ItemChanged(0) ; //////////////////////////////////////////////////////// screenconf = new ScreenConfigurator ( stack , plan ) ; stack -> addWidget ( screenconf ) ; screenconf -> setMeasure ( false ) ; //////////////////////////////////////////////////////// pickLanguage = new TreeWidget ( stack , plan ) ; stack -> addWidget ( pickLanguage ) ; pickLanguage -> setColumnCount ( 1 ) ; pickLanguage -> setHeaderHidden ( true ) ; pickLanguage -> setRootIsDecorated ( false ) ; pickLanguage -> setAlternatingRowColors ( true ) ; nConnect ( pickLanguage , SIGNAL(itemClicked (QTreeWidgetItem*,int)) , this , SLOT (languageClicked(QTreeWidgetItem*,int)) ) ; //////////////////////////////////////////////////////// encryptReport = new TextEdit ( stack , plan ) ; stack -> addWidget ( encryptReport ) ; encryptReport-> setReadOnly ( true ) ; //////////////////////////////////////////////////////// decryptReport = new TextEdit ( stack , plan ) ; stack -> addWidget ( decryptReport ) ; decryptReport-> setReadOnly ( true ) ; //////////////////////////////////////////////////////// depotReport = new TextEdit ( stack , plan ) ; stack -> addWidget ( depotReport ) ; depotReport -> setReadOnly ( true ) ; //////////////////////////////////////////////////////// plainText = new TextEdit ( stack , plan ) ; stack -> addWidget ( plainText ) ; //////////////////////////////////////////////////////// line = new LineEdit ( header , plan ) ; header -> addWidget ( line ) ; //////////////////////////////////////////////////////// lineRename = new LineEdit ( header , plan ) ; header -> addWidget ( lineRename ) ; //////////////////////////////////////////////////////// lineMove = new LineEdit ( header , plan ) ; header -> addWidget ( lineMove ) ; //////////////////////////////////////////////////////// lineDirectory = new LineEdit ( header , plan ) ; header -> addWidget ( lineDirectory ) ; //////////////////////////////////////////////////////// archive = new ArchiveList ( stack , plan ) ; stack -> addWidget ( archive ) ; //////////////////////////////////////////////////////// pickArchive = new ArchivePick ( stack , plan ) ; stack -> addWidget ( pickArchive ) ; //////////////////////////////////////////////////////// help = new WebBrowser ( stack , plan ) ; stack -> addWidget ( help ) ; //////////////////////////////////////////////////////// mdi = new MdiArea ( stack , plan ) ; stack -> addWidget ( mdi ) ; //////////////////////////////////////////////////////// nConnect ( encrypt , SIGNAL(Back ()) , this , SIGNAL(Back ()) ) ; nConnect ( decrypt , SIGNAL(Back ()) , this , SIGNAL(Back ()) ) ; nConnect ( depot , SIGNAL(Back ()) , this , SIGNAL(Back ()) ) ; nConnect ( settings , SIGNAL(Back ()) , this , SIGNAL(Back ()) ) ; nConnect ( srcPicture , SIGNAL(Back ()) , this , SLOT (Encryption()) ) ; nConnect ( keyPicture , SIGNAL(Back ()) , this , SLOT (Encryption()) ) ; nConnect ( getEncrypt , SIGNAL(Back ()) , this , SLOT (Decryption()) ) ; nConnect ( getKeyPic , SIGNAL(Back ()) , this , SLOT (Decryption()) ) ; nConnect ( viewImages , SIGNAL(Back ()) , this , SLOT (Depot ()) ) ; nConnect ( viewEncrypt, SIGNAL(Back ()) , this , SLOT (Depot ()) ) ; nConnect ( viewKeys , SIGNAL(Back ()) , this , SLOT (Depot ()) ) ; nConnect ( fileTool , SIGNAL(Back ()) , this , SLOT (Encryption()) ) ; nConnect ( folderTool , SIGNAL(Back ()) , this , SLOT (MakeFile ()) ) ; nConnect ( textTool , SIGNAL(Back ()) , this , SLOT (AddFile ()) ) ; nConnect ( textEdit , SIGNAL(Back ()) , this , SLOT (BackEdit ()) ) ; nConnect ( audioTool , SIGNAL(Back ()) , this , SLOT (AddFile ()) ) ; nConnect ( folderEdit , SIGNAL(Back ()) , this , SLOT (FolderMenu()) ) ; //////////////////////////////////////////////////////// nConnect ( settings , SIGNAL(Ftp ()) , this , SLOT (Sharing ()) ) ; nConnect ( settings , SIGNAL(Language ()) , this , SLOT (Language ()) ) ; nConnect ( settings , SIGNAL(Fonts ()) , this , SLOT (Fonts ()) ) ; nConnect ( settings , SIGNAL(Display ()) , this , SLOT (Display ()) ) ; nConnect ( settings , SIGNAL(Help ()) , this , SLOT (Help ()) ) ; //////////////////////////////////////////////////////// nConnect ( encrypt , SIGNAL(Files ()) , this , SLOT (MakeFile ()) ) ; nConnect ( encrypt , SIGNAL(Picture ()) , this , SLOT (GetPicture ()) ) ; nConnect ( encrypt , SIGNAL(Key ()) , this , SLOT (PickKey ()) ) ; nConnect ( encrypt , SIGNAL(Encrypt ()) , this , SLOT (DoEncrypt ()) ) ; //////////////////////////////////////////////////////// nConnect ( decrypt , SIGNAL(Picture ()) , this , SLOT (DataPicture ()) ) ; nConnect ( decrypt , SIGNAL(Key ()) , this , SLOT (DataKey ()) ) ; nConnect ( decrypt , SIGNAL(Decrypt ()) , this , SLOT (DoDecrypt ()) ) ; //////////////////////////////////////////////////////// nConnect ( depot , SIGNAL(List ()) , this , SLOT (DepotList ()) ) ; nConnect ( depot , SIGNAL(Pictures ()) , this , SLOT (DepotPictures ()) ) ; nConnect ( depot , SIGNAL(Keys ()) , this , SLOT (DepotKeys ()) ) ; nConnect ( depot , SIGNAL(Encrypted ()) , this , SLOT (DepotEncrypted()) ) ; nConnect ( depot , SIGNAL(Ftp ()) , this , SLOT (DepotFtp ()) ) ; //////////////////////////////////////////////////////// pickPicture = new PickPicture ( stack , plan ) ; stack -> addWidget ( pickPicture ) ; nConnect ( pickPicture,SIGNAL(FileSelected(QString)) , this ,SLOT (FileSelected(QString)) ) ; nConnect ( pickPicture,SIGNAL(FileSelected(QString)) , srcPicture ,SLOT (FileSelected(QString)) ) ; nConnect ( pickPicture,SIGNAL(Full (int,bool)) , srcPicture ,SLOT (Full (int,bool)) ) ; nConnect ( pickPicture,SIGNAL(Empty ()) , srcPicture ,SLOT (Empty ()) ) ; nConnect ( srcPicture ,SIGNAL(Previous ()) , pickPicture,SLOT (Previous ()) ) ; nConnect ( srcPicture ,SIGNAL(Next ()) , pickPicture,SLOT (Next ()) ) ; nConnect ( srcPicture ,SIGNAL(Pick ()) , this ,SLOT (ObtainPic ()) ) ; nConnect ( srcPicture ,SIGNAL(View ()) , this ,SLOT (ViewPicture()) ) ; nConnect ( srcPicture ,SIGNAL(Import ()) , this ,SLOT (ImportPicture()) ) ; nConnect ( pickPicture,SIGNAL(FileSelected(QString)) , keyPicture ,SLOT (FileSelected(QString)) ) ; nConnect ( pickPicture,SIGNAL(Full (int,bool)) , keyPicture ,SLOT (Full (int,bool)) ) ; nConnect ( pickPicture,SIGNAL(Empty ()) , keyPicture ,SLOT (Empty ()) ) ; nConnect ( keyPicture ,SIGNAL(Previous ()) , pickPicture,SLOT (Previous ()) ) ; nConnect ( keyPicture ,SIGNAL(Next ()) , pickPicture,SLOT (Next ()) ) ; nConnect ( keyPicture ,SIGNAL(Pick ()) , this ,SLOT (ObtainKey ()) ) ; nConnect ( keyPicture ,SIGNAL(View ()) , this ,SLOT (ViewPicture()) ) ; nConnect ( keyPicture ,SIGNAL(Import ()) , this ,SLOT (ImportKey ()) ) ; nConnect ( pickPicture,SIGNAL(FileSelected(QString)) , viewImages ,SLOT (FileSelected(QString)) ) ; nConnect ( pickPicture,SIGNAL(Full (int,bool)) , viewImages ,SLOT (Full (int,bool)) ) ; nConnect ( pickPicture,SIGNAL(Empty ()) , viewImages ,SLOT (Empty ()) ) ; nConnect ( viewImages ,SIGNAL(Previous ()) , pickPicture,SLOT (Previous ()) ) ; nConnect ( viewImages ,SIGNAL(Next ()) , pickPicture,SLOT (Next ()) ) ; nConnect ( viewImages ,SIGNAL(View ()) , this ,SLOT (ViewDepot ()) ) ; nConnect ( viewImages ,SIGNAL(Import ()) , this ,SLOT (ImportPicture()) ) ; //////////////////////////////////////////////////////// pickEncrypt = new PickPicture ( stack , plan ) ; stack -> addWidget ( pickEncrypt ) ; nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) , this ,SLOT (FileSelected(QString)) ) ; nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) , getEncrypt ,SLOT (FileSelected(QString)) ) ; nConnect ( pickEncrypt,SIGNAL(Full (int,bool)) , getEncrypt ,SLOT (Full (int,bool)) ) ; nConnect ( pickEncrypt,SIGNAL(Empty ()) , getEncrypt ,SLOT (Empty ()) ) ; nConnect ( getEncrypt ,SIGNAL(Previous ()) , pickEncrypt,SLOT (Previous ()) ) ; nConnect ( getEncrypt ,SIGNAL(Next ()) , pickEncrypt,SLOT (Next ()) ) ; nConnect ( getEncrypt ,SIGNAL(Pick ()) , this ,SLOT (ObtainEncrypted()) ) ; nConnect ( getEncrypt ,SIGNAL(View ()) , this ,SLOT (ViewEncrypted()) ) ; nConnect ( getEncrypt ,SIGNAL(Import ()) , this ,SLOT (ImportEncrypted()) ) ; nConnect ( pickEncrypt,SIGNAL(FileSelected(QString)) , viewEncrypt,SLOT (FileSelected(QString)) ) ; nConnect ( pickEncrypt,SIGNAL(Full (int,bool)) , viewEncrypt,SLOT (Full (int,bool)) ) ; nConnect ( pickEncrypt,SIGNAL(Empty ()) , viewEncrypt,SLOT (Empty ()) ) ; nConnect ( viewEncrypt,SIGNAL(Previous ()) , pickEncrypt,SLOT (Previous ()) ) ; nConnect ( viewEncrypt,SIGNAL(Next ()) , pickEncrypt,SLOT (Next ()) ) ; nConnect ( viewEncrypt,SIGNAL(View ()) , this ,SLOT (ViewDepot ()) ) ; nConnect ( viewEncrypt,SIGNAL(Import ()) , this ,SLOT (ImportEncrypted()) ) ; //////////////////////////////////////////////////////// pickKey = new PickPicture ( stack , plan ) ; stack -> addWidget ( pickKey ) ; nConnect ( pickKey ,SIGNAL(FileSelected(QString)) , this ,SLOT (FileSelected(QString)) ) ; nConnect ( pickKey ,SIGNAL(FileSelected(QString)) , getKeyPic ,SLOT (FileSelected(QString)) ) ; nConnect ( pickKey ,SIGNAL(Full (int,bool)) , getKeyPic ,SLOT (Full (int,bool)) ) ; nConnect ( pickKey ,SIGNAL(Empty ()) , getKeyPic ,SLOT (Empty ()) ) ; nConnect ( getKeyPic ,SIGNAL(Previous ()) , pickKey ,SLOT (Previous ()) ) ; nConnect ( getKeyPic ,SIGNAL(Next ()) , pickKey ,SLOT (Next ()) ) ; nConnect ( getKeyPic ,SIGNAL(Pick ()) , this ,SLOT (ObtainKeys()) ) ; nConnect ( getKeyPic ,SIGNAL(View ()) , this ,SLOT (ViewKeys ()) ) ; nConnect ( getKeyPic ,SIGNAL(Import ()) , this ,SLOT (ImportKeys()) ) ; nConnect ( pickKey ,SIGNAL(FileSelected(QString)) , viewKeys ,SLOT (FileSelected(QString)) ) ; nConnect ( pickKey ,SIGNAL(Full (int,bool)) , viewKeys ,SLOT (Full (int,bool)) ) ; nConnect ( pickKey ,SIGNAL(Empty ()) , viewKeys ,SLOT (Empty ()) ) ; nConnect ( viewKeys ,SIGNAL(Previous ()) , pickKey ,SLOT (Previous ()) ) ; nConnect ( viewKeys ,SIGNAL(Next ()) , pickKey ,SLOT (Next ()) ) ; nConnect ( viewKeys ,SIGNAL(View ()) , this ,SLOT (ViewDepot ()) ) ; nConnect ( viewKeys ,SIGNAL(Import ()) , this ,SLOT (ImportKeys()) ) ; //////////////////////////////////////////////////////// nConnect ( fileTool , SIGNAL(New ()) , this , SLOT (NewFile ()) ) ; nConnect ( fileTool , SIGNAL(Add ()) , this , SLOT (AddFile ()) ) ; nConnect ( fileTool , SIGNAL(Remove ()) , this , SLOT (RemoveFile ()) ) ; nConnect ( fileTool , SIGNAL(Packaging ()) , this , SLOT (CreatePackage()) ) ; //////////////////////////////////////////////////////// nConnect ( folderTool , SIGNAL(Join ()) , this , SLOT (FolderJoin ()) ) ; nConnect ( folderTool , SIGNAL(Edit ()) , this , SLOT (FolderEdit ()) ) ; nConnect ( folderTool , SIGNAL(Delete ()) , this , SLOT (FolderDelete ()) ) ; nConnect ( folderTool , SIGNAL(Text ()) , this , SLOT (FolderText ()) ) ; nConnect ( folderTool , SIGNAL(Recorder ()) , this , SLOT (FolderRecorder()) ) ; //////////////////////////////////////////////////////// nConnect ( folderList , SIGNAL(CdUp ()) , pickArchive , SLOT (CdUp ()) ) ; nConnect ( folderList , SIGNAL(Directory(QString)) , pickArchive , SLOT (Directory(QString)) ) ; nConnect ( pickArchive , SIGNAL(Folders(bool,QStringList)) , folderList , SLOT (Folders(bool,QStringList)) ) ; nConnect ( pickArchive , SIGNAL(Listing ()) , this , SLOT (FolderListing ()) ) ; nConnect ( pickArchive , SIGNAL(Ready ()) , this , SLOT (FolderReady ()) ) ; nConnect ( pickArchive , SIGNAL(selectionChanged()) , this , SLOT (FolderSelected ()) ) ; nConnect ( archive , SIGNAL(selectionChanged()) , this , SLOT (FileSelected ()) ) ; //////////////////////////////////////////////////////// nConnect ( textTool , SIGNAL(New ()) , this , SLOT (FolderText()) ) ; nConnect ( textTool , SIGNAL(Save ()) , this , SLOT (SaveText ()) ) ; //////////////////////////////////////////////////////// nConnect ( textEdit , SIGNAL(New ()) , this , SLOT (NewEdit ()) ) ; nConnect ( textEdit , SIGNAL(Save ()) , this , SLOT (SaveEdit ()) ) ; //////////////////////////////////////////////////////// nConnect ( lineRename , SIGNAL(returnPressed ()) , this , SLOT (RenameAction ()) ) ; nConnect ( lineMove , SIGNAL(returnPressed ()) , this , SLOT (MoveAction ()) ) ; nConnect ( lineDirectory , SIGNAL(returnPressed ()) , this , SLOT (DirectoryAction()) ) ; nConnect ( lineRename , SIGNAL(editingFinished()) , this , SLOT (FolderBack ()) ) ; nConnect ( lineMove , SIGNAL(editingFinished()) , this , SLOT (FolderBack ()) ) ; nConnect ( lineDirectory , SIGNAL(editingFinished()) , this , SLOT (FolderBack ()) ) ; //////////////////////////////////////////////////////// nConnect ( folderEdit , SIGNAL(Rename ()) , this , SLOT (FileRename ()) ) ; nConnect ( folderEdit , SIGNAL(Move ()) , this , SLOT (FileMove ()) ) ; nConnect ( folderEdit , SIGNAL(Directory ()) , this , SLOT (FileDirectory ()) ) ; nConnect ( folderEdit , SIGNAL(Edit ()) , this , SLOT (EditText ()) ) ; nConnect ( folderEdit , SIGNAL(Ftp ()) , this , SLOT (FileFtp ()) ) ; //////////////////////////////////////////////////////// } void N::PaintingSecretGui::BootupFtp(void) { if ( ! plan -> Booleans [ "Desktop" ] ) { if (ftp->AutoStartup()) ftp->begin(true) ; } ; } void N::PaintingSecretGui::FileSelected(QString path) { label -> setText ( path ) ; } void N::PaintingSecretGui::AndroidPathes(void) { #define AFP(NX) N::FtpSettings::addFolder(plan->Path("files/" NX),QString(NX),true) ; \ if (debug) qDebug ( plan->Path("files/" NX).toUtf8().constData() ) AFP ( "Documents" ) ; AFP ( "Download" ) ; AFP ( "Encryption" ) ; AFP ( "Files" ) ; AFP ( "Images" ) ; AFP ( "Keys" ) ; AFP ( "Upload" ) ; if (debug) { AFP ( "Temp" ) ; AFP ( "Sounds" ) ; AFP ( "Users" ) ; } ; #undef AFP } void N::PaintingSecretGui::ApplePathes(void) { #define AFP(NX) N::FtpSettings::addFolder(plan->Path("Documents/" NX),QString(NX),true) ; \ if (debug) qDebug ( plan->Path("Documents/" NX).toUtf8().constData() ) AFP ( "Documents" ) ; AFP ( "Download" ) ; AFP ( "Encryption" ) ; AFP ( "Files" ) ; AFP ( "Images" ) ; AFP ( "Keys" ) ; AFP ( "Upload" ) ; if (debug) { AFP ( "Temp" ) ; AFP ( "Sounds" ) ; AFP ( "Users" ) ; } ; #undef AFP } void N::PaintingSecretGui::InstallPathes(void) { if ( plan -> Booleans [ "Desktop" ] ) { pickPicture -> setRoot ( plan->Path("Images" ) ) ; pickEncrypt -> setRoot ( plan->Path("Download") ) ; pickKey -> setRoot ( plan->Path("Upload" ) ) ; archive -> setRoot ( plan->Path("Files" ) ) ; pickArchive -> setRoot ( plan->Path("Files" ) ) ; } else { #ifdef Q_OS_ANDROID pickPicture -> setRoot ( plan->Path("files/Images" ) ) ; pickEncrypt -> setRoot ( plan->Path("files/Encryption") ) ; pickKey -> setRoot ( plan->Path("files/Keys" ) ) ; archive -> setRoot ( plan->Path("files/Documents" ) ) ; pickArchive -> setRoot ( plan->Path("files/Documents" ) ) ; #endif #ifdef Q_OS_IOS pickPicture -> setRoot ( plan->Path("Documents/Images" ) ) ; pickEncrypt -> setRoot ( plan->Path("Documents/Encryption") ) ; pickKey -> setRoot ( plan->Path("Documents/Keys" ) ) ; archive -> setRoot ( plan->Path("Documents/Documents" ) ) ; pickArchive -> setRoot ( plan->Path("Documents/Documents" ) ) ; #endif } ; } void N::PaintingSecretGui::relocation(void) { } QString N::PaintingSecretGui::LanguagePath(QString filename) { QString LC ; LidTo(plan->LanguageId,LC) ; QString p = QString("Translations/%1/%2").arg(LC).arg(filename) ; return Root.absoluteFilePath(p) ; } void N::PaintingSecretGui::Encryption(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( encryptReport ) ; menu -> setCurrentWidget ( encrypt ) ; label -> setText ( tr("Encrypt data into a picture") ) ; ////////////////////////////////////////////////////////////////// QString p = LanguagePath("steganoencrypt.html") ; QFileInfo F(p) ; if (!F.exists()) return ; QByteArray Body ; File::toByteArray ( p , Body ) ; encryptReport -> clear ( ) ; encryptReport -> append ( QString::fromUtf8(Body) ) ; encryptReport -> verticalScrollBar ( ) -> setValue ( 0 ) ; } void N::PaintingSecretGui::Decryption(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( decryptReport ) ; menu -> setCurrentWidget ( decrypt ) ; label -> setText ( tr("Decrypt data from picture") ) ; //////////////////////////////////////////////////////////////// QString p = LanguagePath("steganodecrypt.html") ; QFileInfo F(p) ; if (!F.exists()) return ; QByteArray Body ; File::toByteArray ( p , Body ) ; decryptReport -> clear ( ) ; decryptReport -> append ( QString::fromUtf8(Body) ) ; decryptReport -> verticalScrollBar ( ) -> setValue ( 0 ) ; } void N::PaintingSecretGui::Depot(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( depotReport ) ; menu -> setCurrentWidget ( depot ) ; label -> setText ( tr("Painting secrets depot") ) ; ///////////////////////////////////////////////////////////// QString p = LanguagePath("steganodepot.html") ; QFileInfo F(p) ; if (!F.exists()) return ; QByteArray Body ; File::toByteArray ( p , Body ) ; depotReport -> clear ( ) ; depotReport -> append ( QString::fromUtf8(Body) ) ; depotReport -> verticalScrollBar ( ) -> setValue ( 0 ) ; } void N::PaintingSecretGui::Settings(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( ftp ) ; menu -> setCurrentWidget ( settings ) ; label -> setText ( tr("Painting secrets settings") ) ; } void N::PaintingSecretGui::Sharing(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( ftp ) ; menu -> setCurrentWidget ( settings ) ; label -> setText ( tr("Ftp sharing server") ) ; Alert ( Error ) ; ////////////////////////////////////////////////////////////////////////////// QHostInfo info ; QString qstr = info.localHostName() ; QHostInfo info2 ( QHostInfo ::fromName ( qstr ) ) ; QList<QHostAddress> list ; bool found = false ; list = info2.addresses() ; if (list.count()<=0) list = QNetworkInterface::allAddresses() ; ////////////////////////////////////////////////////////////////////////////// for (int i=0;!found && i<list.count();i++) { if (!list[i].isLoopback()) { if (list[i].protocol() == QAbstractSocket::IPv4Protocol) { label -> setText ( tr("Local address : %1") .arg(list[i].toString()) ) ; found = true ; } ; } ; } ; } void N::PaintingSecretGui::Fonts(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( fontconf ) ; menu -> setCurrentWidget ( settings ) ; label -> setText ( tr("Setup fonts") ) ; Alert ( Error ) ; } void N::PaintingSecretGui::Language(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickLanguage ) ; menu -> setCurrentWidget ( settings ) ; ListLanguage ( ) ; Alert ( Error ) ; } void N::PaintingSecretGui::languageClicked(QTreeWidgetItem * item,int column) { Q_UNUSED ( column ) ; for (int i=0;i<pickLanguage->topLevelItemCount();i++) { QTreeWidgetItem * it = pickLanguage->topLevelItem(i) ; if (it==item) { QString s = it->text(0) ; QString m ; int l = item->data(0,Qt::UserRole).toInt() ; it -> setIcon ( 0 , QIcon(":/images/yes.png" ) ) ; it -> setData ( 0 , Qt::UserRole+1 , 1 ) ; plan -> settings . beginGroup ( "System" ) ; plan -> settings . setValue ( "Language" , l ) ; plan -> settings . endGroup ( ) ; m = tr("Language change to %1 will take effect after restart").arg(s) ; label -> setText ( m ) ; } else { it -> setIcon ( 0 , QIcon(":/icons/empty.png") ) ; it -> setData ( 0 , Qt::UserRole+1 , 0 ) ; } ; } ; } void N::PaintingSecretGui::ListLanguage(void) { int LID ; menu -> setEnabled ( false ) ; pickLanguage -> clear ( ) ; ForLanguage ( LID , plan->languages.Supports ) ; QString LC ; if (LidTo(LID,LC) || LID==1819) { QString p = QString("Translations/%1/%2").arg(LC).arg(QM) ; p = Root.absoluteFilePath(p) ; QFileInfo F(p) ; if (F.exists() || LID==1819) { QString n = (plan->languages)[LID] ; NewTreeWidgetItem ( IT ) ; IT -> setData ( 0 , Qt::UserRole , LID ) ; IT -> setText ( 0 , n ) ; if (LID==plan->LanguageId) { IT -> setIcon ( 0 , QIcon(":/images/yes.png" )) ; IT -> setData ( 0 , Qt::UserRole+1 , 1 ) ; } else { IT -> setIcon ( 0 , QIcon(":/icons/empty.png" )) ; IT -> setData ( 0 , Qt::UserRole+1 , 0 ) ; } ; pickLanguage -> addTopLevelItem ( IT ) ; } ; } ; if (debug) { QString nn = (plan->languages)[LID] ; qDebug ( nn.toUtf8().constData() ) ; } ; EndLanguage ( LID , plan->languages.Supports ) ; QString l = (plan->languages)[plan->LanguageId] ; QString m ; m = tr("Setup language, current language is %1").arg(l) ; label -> setText ( m ) ; menu -> setEnabled ( true ) ; } void N::PaintingSecretGui::Display(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( screenconf ) ; menu -> setCurrentWidget ( settings ) ; label -> setText ( tr("Setup display size") ) ; Alert ( Error ) ; } void N::PaintingSecretGui::Help(void) { emit Manual ( ) ; } void N::PaintingSecretGui::MakeFile(void) { if (packaging<=0) packaging = ObtainUuid ( ) ; header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( archive ) ; menu -> setCurrentWidget ( fileTool ) ; QString m ; m = tr("Create data package, signature is `%1`.").arg(packaging) ; label -> setText ( m ) ; fileTool -> setDeletion ( archive->Selections () > 0 ) ; fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ; Alert ( Error ) ; } SUID N::PaintingSecretGui::ObtainUuid(void) { SUID u = 0 ; SqlConnection SC(plan->sql) ; if (SC.open("PaintingSecretGui","ObtainUuid")) { u = SC.Unique (PlanTable(MajorUuid),"uuid") ; SC.close() ; } ; SC.remove() ; return u ; } void N::PaintingSecretGui::NewFile(void) { if (packaging>0) { QString t = QString("Temp/%1.tar.xz").arg(packaging) ; t = Root.absoluteFilePath(t) ; QFile::remove(t) ; } ; packaging = ObtainUuid ( ) ; archive -> clear ( ) ; header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( archive ) ; menu -> setCurrentWidget ( fileTool ) ; QString m ; m = tr("Create data package, signature is `%1`.").arg(packaging ) ; label -> setText ( m ) ; fileTool -> setDeletion ( archive->Selections () > 0 ) ; fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ; Alert ( Error ) ; } void N::PaintingSecretGui::AddFile(void) { header -> setCurrentWidget ( folderList ) ; stack -> setCurrentWidget ( pickArchive ) ; menu -> setCurrentWidget ( folderTool ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; } void N::PaintingSecretGui::RemoveFile(void) { archive -> Delete ( ) ; fileTool -> setDeletion ( archive->Selections () > 0 ) ; fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ; } void N::PaintingSecretGui::CreatePackage(void) { XDEBUG ( "N::PaintingSecretGui::CreatePackage" ) ; ////////////////////////////////////////// if (packaging<=0) return ; ////////////////////////////////////////// header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( archive ) ; menu -> setCurrentWidget ( fileTool ) ; ////////////////////////////////////////// QStringList L = archive -> PickFiles( ) ; if (L.count()<=0) return ; ////////////////////////////////////////// QString m ; m = tr("Compress %1") . arg( packaging ) ; label -> setText ( m ) ; stack -> setEnabled ( false ) ; menu -> setEnabled ( false ) ; plan -> processEvents ( ) ; ////////////////////////////////////////// XDEBUG ( "N::PaintingSecretGui::CreatePackage@Bale" ) ; ////////////////////////////////////////// QString XZ ; VirtualIO IO ; XZ = QString("%1.tar.xz").arg(packaging) ; XZ = QString("Temp/%1" ).arg(XZ ) ; XZ = Root.absoluteFilePath (XZ ) ; IO . setDirectory ( archive -> Path() ) ; IO . setFile ( File::Xz ) ; IO . setVIO ( VirtualDisk::Tar ) ; IO . append ( L ) ; #if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) qDebug ( "N::PaintingSecretGui::[email protected]" ) ; #endif IO . Bale ( XZ ) ; ////////////////////////////////////////// XDEBUG ( "N::PaintingSecretGui::CreatePackage@Display" ) ; ////////////////////////////////////////// QFileInfo F(XZ) ; m = tr("Compressed data size is %1").arg(F.size()) ; label -> setText ( m ) ; ////////////////////////////////////////// plan -> processEvents ( ) ; stack -> setEnabled ( true ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; ////////////////////////////////////////// Alert ( Error ) ; } void N::PaintingSecretGui::FileSelected(void) { fileTool -> setDeletion ( archive->Selections () > 0 ) ; fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ; } void N::PaintingSecretGui::FolderJoin(void) { QStringList L = pickArchive -> PickFiles ( ) ; if (L.count()<=0) return ; header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( archive ) ; menu -> setCurrentWidget ( fileTool ) ; plan -> processEvents ( ) ; archive -> Append ( L ) ; plan -> processEvents ( ) ; fileTool -> setDeletion ( archive->Selections () > 0 ) ; fileTool -> setPackaging ( archive->topLevelItemCount() > 0 ) ; } void N::PaintingSecretGui::FolderEdit(void) { menu -> setCurrentWidget ( folderEdit ) ; Alert ( Click ) ; } void N::PaintingSecretGui::FolderMenu(void) { menu -> setCurrentWidget ( folderTool ) ; Alert ( Click ) ; } void N::PaintingSecretGui::DeletePath(QDir & root,QStringList files) { QString S ; foreach (S,files) { QFileInfo F ( S ) ; if (F.isDir()) { QDir D ( S ) ; QFileInfoList L ; QStringList M ; QString p = S ; p = root.relativeFilePath(p) ; L = D.entryInfoList ( QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks ) ; for (int i=0;i<L.count();i++) { M << L[i].absoluteFilePath() ; } ; DeletePath ( root , M ) ; label->setText(tr("Delete %1").arg(p)) ; root . rmpath ( S ) ; } else if (F.isFile()) { QString p = S ; p = root.relativeFilePath(p) ; label->setText(tr("Delete %1").arg(p)) ; QFile::remove(S) ; } ; plan -> processEvents ( ) ; } ; } void N::PaintingSecretGui::FolderDelete(void) { QStringList L = pickArchive -> PickFiles ( ) ; if (L.count()<=0) return ; folderTool -> setEnabled ( false ) ; header -> setCurrentWidget ( label ) ; plan -> processEvents ( ) ; QDir r = pickArchive->Path ( ) ; DeletePath ( r , L ) ; header -> setCurrentWidget ( folderList ) ; folderTool -> setEnabled ( true ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; } void N::PaintingSecretGui::FolderText(void) { emit NewText ( pickArchive -> Path() , pickArchive -> CurrentPath() ) ; #ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX plainText -> clear ( ) ; header -> setCurrentWidget ( line ) ; stack -> setCurrentWidget ( plainText ) ; menu -> setCurrentWidget ( textTool ) ; label -> setText ( tr("Plain text editor" ) ) ; //////////////////////////////////////////////////////////// bool e = false ; QDir r = pickArchive -> Path ( ) ; QDir c = pickArchive -> CurrentPath ( ) ; QString f = tr("Noname") ; QString t ; int i = 1 ; do { t = QString("%1-%2.txt").arg(f).arg(i) ; i++ ; t = c.absoluteFilePath(t) ; QFileInfo F(t) ; if (!F.exists()) { t = r.relativeFilePath(t) ; e = true ; } ; } while (!e) ; line -> blockSignals ( true ) ; line -> setText ( t ) ; line -> blockSignals ( false ) ; //////////////////////////////////////////////////////////// Alert ( Error ) ; #endif } void N::PaintingSecretGui::SaveText(void) { QString note = line->text() ; if (note.length()<=0) return ; QDir r = pickArchive -> Path( ) ; QString file = r.absoluteFilePath ( note ) ; QString head = r.absoluteFilePath ( "" ) ; if (!file.contains(head)) return ; QString text = plainText -> toPlainText ( ) ; QByteArray body = text . toUtf8 ( ) ; QFileInfo fdir ( file ) ; r . mkpath ( fdir . absolutePath ( ) ) ; File :: toFile ( file , body ) ; AddFile ( ) ; } void N::PaintingSecretGui::FolderRecorder(void) { QString path = pickArchive->CurrentPath().absoluteFilePath("") ; emit Recording ( path ) ; } void N::PaintingSecretGui::FolderListing(void) { folderList -> setEnabled ( false ) ; folderTool -> setEnabled ( false ) ; } void N::PaintingSecretGui::FolderReady(void) { folderList -> setEnabled ( true ) ; folderTool -> setEnabled ( true ) ; FolderSelected ( ) ; } void N::PaintingSecretGui::FolderSelected(void) { QTreeWidgetItem * item = pickArchive->currentItem ( ) ; bool isText = false ; if (NotNull(item)) { int t = item->data(1,Qt::UserRole).toInt() ; if (t==0) { QFileInfo F(item->text(0)) ; QString S = F.suffix() ; S = S.toLower() ; isText = ( S == "txt" ) ; } ; } ; folderTool -> setSelected ( pickArchive->Selections() ) ; folderEdit -> setSelected ( pickArchive->Selections() ) ; folderEdit -> setEdit ( isText ) ; } void N::PaintingSecretGui::GetPicture(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickPicture ) ; menu -> setCurrentWidget ( srcPicture ) ; label -> setText ( tr("Pick picture for encryption") ) ; Alert ( Error ) ; srcPicture -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickPicture -> Index = 0 ; pickPicture -> Refresh ( ) ; srcPicture -> setEnabled ( true ) ; } void N::PaintingSecretGui::PickKey(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickPicture ) ; menu -> setCurrentWidget ( keyPicture ) ; label -> setText ( tr("Pick a picture as key") ) ; Alert ( Error ) ; keyPicture -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickPicture -> Index = 0 ; pickPicture -> Refresh ( ) ; keyPicture -> setEnabled ( true ) ; } void N::PaintingSecretGui::DoEncrypt(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( encryptReport ) ; menu -> setCurrentWidget ( encrypt ) ; menu -> setEnabled ( false ) ; //////////////////////////////////////////////////////////////// QString m ; QString rp ; m = tr("Creating steganographic picture `%1`.").arg(packaging) ; label -> setText ( m ) ; //////////////////////////////////////////////////////////////// encryptReport -> clear ( ) ; plan -> processEvents ( ) ; Alert ( Click ) ; //////////////////////////////////////////////////////////////// bool hasData = false ; QByteArray XzData ; QByteArray PackData ; QByteArray KeyData ; QString XZ ; QImage SrcImage ; QImage KeyImage ; //////////////////////////////////////////////////////////////// if (packaging>0) { XZ = QString("Temp/%1.tar.xz").arg(packaging) ; XZ = Root.absoluteFilePath ( XZ ) ; QFileInfo F ( XZ ) ; if (F.exists() && F.size()>0) { if (F.size()<(8*1024*1024)) { File :: toByteArray ( XZ , XzData ) ; if (XzData.size()==F.size()) { hasData = true ; m = tr ( "Compressed data size for %1 is %2" ) . arg ( packaging ) . arg ( F.size() ) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; } else { m = tr ( "Failure to read compressed data" ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; } else { m = tr ( "Compressed data size %1 exceeds limit %2" ) . arg ( F.size() ) . arg ( (8*1024*1024) ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; } ; } ; if (!hasData) { m = tr("You did not specify the data you want to encrypt." ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; //////////////////////////////////////////////////////////////// if (SourcePicture.length()<=0) { m = tr("You did not specify your source picture." ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; rp = SourcePicture ; rp = Root.relativeFilePath(rp) ; m = tr("Source image filename is `%1`").arg(rp) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; if (!SrcImage.load(SourcePicture) || SrcImage . width ( ) <= 0 || SrcImage . height ( ) <= 0 ) { m = tr("Source picture can not be loaded." ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; m = tr("Source image size is %1 x %2").arg(SrcImage.width()).arg(SrcImage.height()) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; //////////////////////////////////////////////////////////////// if (KeyPicture.length()<=0) { m = tr("You did not specify your key picture." ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; rp = KeyPicture ; rp = Root.relativeFilePath(rp) ; m = tr("Key image filename is `%1`").arg(rp) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; if (!KeyImage.load(KeyPicture) || KeyImage . width ( ) <= 0 || KeyImage . height ( ) <= 0 ) { m = tr("Key picture can not be loaded." ) ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; m = tr("Key image size is %1 x %2").arg(KeyImage.width()).arg(KeyImage.height()) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; //////////////////////////////////////////////////////////////// bool encrypted = false ; if (Images::EncryptPair(packaging,XzData,PackData,KeyData)) { encrypted = true ; if ( PackData . size ( ) <= 0 ) encrypted = false ; if ( KeyData . size ( ) <= 0 ) encrypted = false ; } ; if (!encrypted) { m = tr("Encryption failure") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; //////////////////////////////////////////////////////////////// QDir K ; QDir E ; if ( plan -> Booleans [ "Desktop" ] ) { K = QDir ( Root.absoluteFilePath("Upload" ) ) ; E = QDir ( Root.absoluteFilePath("Download" ) ) ; } else { K = QDir ( Root.absoluteFilePath("Keys" ) ) ; E = QDir ( Root.absoluteFilePath("Encryption") ) ; } ; //////////////////////////////////////////////////////////////// if (PackData.size()>0) { QImage O ; if (N::Images::Embedded(SrcImage,O,PackData)) { QString FO = QString("PSH-%1.png").arg(packaging) ; FO = E . absoluteFilePath ( FO ) ; if ( O . save ( FO ) ) { QString XP ; XP = FO ; XP = Root.relativeFilePath ( XP ) ; m = tr("Steganographic picture saved at `%1`.").arg(XP) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; } else { m = tr("Steganographic picture can not be saved.") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; Alert ( Error ) ; plan -> processEvents ( ) ; return ; } ; } else { m = tr("Data is too big to fit into the picture.") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; } ; //////////////////////////////////////////////////////////////// if (KeyData .size()>0) { QImage O ; if (N::Images::Embedded(KeyImage,O,KeyData)) { QString FO = QString("KEY-%1.png").arg(packaging) ; FO = K . absoluteFilePath ( FO ) ; if ( O . save ( FO ) ) { QString XP ; XP = FO ; XP = Root.relativeFilePath ( XP ) ; m = tr("Steganographic key saved at `%1`.").arg(XP) ; encryptReport -> append ( m ) ; plan -> processEvents ( ) ; } else { m = tr("Steganographic key can not be saved.") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; } else { m = tr("Key data is too big to fit into the picture.") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; } ; //////////////////////////////////////////////////////////////// if (XZ.length()>0) { QFileInfo FXZ ( XZ ) ; if (FXZ.exists()) QFile :: remove ( XZ ) ; } ; //////////////////////////////////////////////////////////////// if ( ! plan -> Booleans [ "Desktop" ] ) { SqlConnection SC ( plan -> sql ) ; if (SC.open("PaintingSecretGui","DoEncrypt")) { SC . assureUuid ( PlanTable(MajorUuid) , packaging , 260 ) ; SC . close ( ) ; } ; SC . remove ( ) ; } ; //////////////////////////////////////////////////////////////// SourcePicture = "" ; KeyPicture = "" ; //////////////////////////////////////////////////////////////// m = tr("Encryption successful, please go to `Depot` to see the results, or use FTP upload to your target machine.") ; encryptReport -> append ( m ) ; m = tr("Do not change the image file format, otherwise the data hidden in the picture will be lost.") ; encryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; } void N::PaintingSecretGui::DataPicture(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickEncrypt ) ; menu -> setCurrentWidget ( getEncrypt ) ; label -> setText ( tr("Pick picture for decryption") ) ; Alert ( Error ) ; getEncrypt -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickEncrypt -> Index = 0 ; pickEncrypt -> Refresh ( ) ; getEncrypt -> setEnabled ( true ) ; } void N::PaintingSecretGui::DataKey(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickKey ) ; menu -> setCurrentWidget ( getKeyPic ) ; label -> setText ( tr("Pick key picture for decryption") ) ; Alert ( Error ) ; getKeyPic -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickKey -> Index = 0 ; pickKey -> Refresh ( ) ; getKeyPic -> setEnabled ( true ) ; } void N::PaintingSecretGui::DoDecrypt(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( decryptReport ) ; menu -> setCurrentWidget ( decrypt ) ; menu -> setEnabled ( false ) ; ////////////////////////////////////////////////////////////////////////// QString m ; QString rp ; decryptReport -> clear ( ) ; plan -> processEvents ( ) ; if (DecryptPicture.length()<=0) { m = tr("You did not specify your encrypted picture." ) ; decryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; ////////////////////////////////////////////////////////////////////////// QFileInfoList L = pickKey->Root.entryInfoList ( QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks ) ; QStringList S ; for (int i=0;i<L.count();i++) S << L[i].fileName() ; ////////////////////////////////////////////////////////////////////////// if (DecryptKey.length()>0) { int index = S . indexOf ( DecryptKey ) ; if (index>=0) S . takeAt ( index ) ; S . prepend ( DecryptKey ) ; } ; if (S.count()<=0) { m = tr("No decryption picture found.") ; decryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; ////////////////////////////////////////////////////////////////////////// QImage SRC ; QImage KEY ; QByteArray Body ; SUID srid = 0 ; bool correct = true ; rp = pickEncrypt->Root.absoluteFilePath ( DecryptPicture ) ; if (!SRC.load(rp)) correct = false ; if (correct) { if (!Images::Extract(SRC,Body)) correct = false ; } ; if (correct) { int t = Images::DecryptPair(Body,srid) ; if (t!=1) correct = false ; } ; if (!correct) { m = tr("Decryption failure.") ; decryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; ////////////////////////////////////////////////////////////////////////// correct = false ; for (int i=0;!correct && i<S.count();i++) { QString s = S[i] ; rp = pickKey->Root.absoluteFilePath(s) ; KEY = QImage() ; if (KEY.load(rp)) { QByteArray KB ; decryptReport -> append ( s ) ; plan -> processEvents ( ) ; if (Images::Extract(KEY,KB)) { SUID krid = 0 ; int t = Images::DecryptPair(KB,krid) ; if (t==0 && krid==srid) { QByteArray XZB ; if (Images::DecryptBody(srid,XZB,Body,KB)) { if (XZB.size()>0) { QString fs = QString("Temp/%1.tar.xz").arg(srid) ; fs = Root.absoluteFilePath(fs) ; File :: toFile ( fs , XZB ) ; QString dd = QString("Files/%1").arg(srid) ; dd = Root.absoluteFilePath ( dd ) ; VirtualIO VIO ; QDir vdd ( dd ) ; VIO . setDirectory ( vdd ) ; VIO . setFile ( File::Xz ) ; VIO . setVIO ( VirtualDisk::Tar ) ; VIO . setFileName ( fs ) ; VIO . Unpack ( ) ; m = tr("Decrypt %1 successful").arg(srid) ; decryptReport -> append ( m ) ; if (VIO.files.count()>0) { m = "===================" ; decryptReport -> append ( m ) ; m = tr("Decrypted files") ; decryptReport -> append ( m ) ; m = "===================" ; decryptReport -> append ( m ) ; plan -> processEvents ( ) ; for (int i=0;i<VIO.files.count();i++) { m = QString("Files/%1/%2").arg(srid).arg(VIO.files[i].Filename) ; decryptReport -> append ( m ) ; plan -> processEvents ( ) ; } ; m = "===================" ; decryptReport -> append ( m ) ; plan -> processEvents ( ) ; m = tr("Please use FTP download to your machine for usage.") ; decryptReport -> append ( m ) ; plan -> processEvents ( ) ; } ; QFile :: remove ( fs ) ; correct = true ; } ; } ; } ; } ; } ; } ; if (!correct) { m = tr("Decryption failure.") ; decryptReport -> append ( m ) ; menu -> setEnabled ( true ) ; plan -> processEvents ( ) ; Alert ( Error ) ; return ; } ; ////////////////////////////////////////////////////////////////////////// DecryptPicture = "" ; DecryptKey = "" ; ////////////////////////////////////////////////////////////////////////// menu -> setEnabled ( true ) ; Alert ( Error ) ; } void N::PaintingSecretGui::DepotList(void) { emit FullDepot ( ) ; } void N::PaintingSecretGui::DepotPictures(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickPicture ) ; menu -> setCurrentWidget ( viewImages ) ; label -> setText ( tr("Pictures") ) ; Alert ( Error ) ; viewImages -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickPicture -> Index = 0 ; pickPicture -> Refresh ( ) ; viewImages -> setEnabled ( true ) ; /////////////////////////////////////////////// BackWidget = pickPicture ; BackMenu = viewImages ; ReturnLabel = tr("Pictures") ; } void N::PaintingSecretGui::DepotKeys(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickKey ) ; menu -> setCurrentWidget ( viewKeys ) ; label -> setText ( tr("Decryption key pictures") ) ; Alert ( Error ) ; viewKeys -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickKey -> Index = 0 ; pickKey -> Refresh ( ) ; viewKeys -> setEnabled ( true ) ; ////////////////////////////////////////////////////////////// BackWidget = pickKey ; BackMenu = viewKeys ; ReturnLabel = tr("Decryption key pictures") ; } void N::PaintingSecretGui::DepotEncrypted(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickEncrypt ) ; menu -> setCurrentWidget ( viewEncrypt ) ; label -> setText ( tr("Encrypted pictures") ) ; Alert ( Error ) ; viewEncrypt -> setEnabled ( false ) ; plan -> processEvents ( ) ; pickEncrypt -> Index = 0 ; pickEncrypt -> Refresh ( ) ; viewEncrypt -> setEnabled ( true ) ; ///////////////////////////////////////////////////////// BackWidget = pickEncrypt ; BackMenu = viewEncrypt ; ReturnLabel = tr("Encrypted pictures") ; } void N::PaintingSecretGui::DepotFtp(void) { emit FullFtp ( ) ; } void N::PaintingSecretGui::ViewPicture(void) { QString path ; if (!pickPicture->CurrentPath(path)) return ; QString file = pickPicture->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; picTool = new PaintingViewTool ( menu , plan ) ; vcf = new VcfView ( stack , plan ) ; menu -> addWidget ( picTool ) ; stack -> addWidget ( vcf ) ; menu -> setCurrentWidget ( picTool ) ; stack -> setCurrentWidget ( vcf ) ; header -> setCurrentWidget ( label ) ; plan -> processEvents ( ) ; vcf -> ViewPicture ( IFG , NULL ) ; vcf -> resize ( stack->size() ) ; Alert ( Done ) ; //////////////////////////////////////////////////////////// vcf -> skipMouse = true ; nConnect ( picTool , SIGNAL(Back ()) , this , SLOT (ReturnPick()) ) ; nConnect ( picTool , SIGNAL(ZoomIn ()) , vcf , SLOT (ZoomIn ()) ) ; nConnect ( picTool , SIGNAL(ZoomOut ()) , vcf , SLOT (ZoomOut ()) ) ; } void N::PaintingSecretGui::ReturnPick(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickPicture ) ; menu -> setCurrentWidget ( srcPicture ) ; label -> setText ( tr("Pick picture for encryption") ) ; Alert ( Error ) ; /////////////////////////////////////////////////////////////////// picTool -> deleteLater ( ) ; vcf -> deleteLater ( ) ; /////////////////////////////////////////////////////////////////// picTool = NULL ; vcf = NULL ; } void N::PaintingSecretGui::ViewEncrypted(void) { QString path ; if (!pickEncrypt->CurrentPath(path)) return ; QString file = pickEncrypt->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; picTool = new PaintingViewTool ( menu , plan ) ; vcf = new VcfView ( stack , plan ) ; menu -> addWidget ( picTool ) ; stack -> addWidget ( vcf ) ; menu -> setCurrentWidget ( picTool ) ; stack -> setCurrentWidget ( vcf ) ; header -> setCurrentWidget ( label ) ; plan -> processEvents ( ) ; vcf -> ViewPicture ( IFG , NULL ) ; vcf -> resize ( stack->size() ) ; Alert ( Done ) ; //////////////////////////////////////////////////////////// vcf -> skipMouse = true ; nConnect ( picTool , SIGNAL(Back ()) , this , SLOT (ReturnEncrypted()) ) ; nConnect ( picTool , SIGNAL(ZoomIn ()) , vcf , SLOT (ZoomIn ()) ) ; nConnect ( picTool , SIGNAL(ZoomOut ()) , vcf , SLOT (ZoomOut ()) ) ; } void N::PaintingSecretGui::ReturnEncrypted(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickEncrypt ) ; menu -> setCurrentWidget ( getEncrypt ) ; label -> setText ( tr("Pick picture for decryption") ) ; Alert ( Error ) ; /////////////////////////////////////////////////////////////////// picTool -> deleteLater ( ) ; vcf -> deleteLater ( ) ; /////////////////////////////////////////////////////////////////// picTool = NULL ; vcf = NULL ; } void N::PaintingSecretGui::ViewKeys(void) { QString path ; if (!pickKey->CurrentPath(path)) return ; QString file = pickKey->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; picTool = new PaintingViewTool ( menu , plan ) ; vcf = new VcfView ( stack , plan ) ; menu -> addWidget ( picTool ) ; stack -> addWidget ( vcf ) ; menu -> setCurrentWidget ( picTool ) ; stack -> setCurrentWidget ( vcf ) ; header -> setCurrentWidget ( label ) ; plan -> processEvents ( ) ; vcf -> ViewPicture ( IFG , NULL ) ; vcf -> resize ( stack->size() ) ; Alert ( Done ) ; //////////////////////////////////////////////////////////// vcf -> skipMouse = true ; nConnect ( picTool , SIGNAL(Back ()) , this , SLOT (ReturnKeys()) ) ; nConnect ( picTool , SIGNAL(ZoomIn ()) , vcf , SLOT (ZoomIn ()) ) ; nConnect ( picTool , SIGNAL(ZoomOut ()) , vcf , SLOT (ZoomOut ()) ) ; } void N::PaintingSecretGui::ReturnKeys(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( pickKey ) ; menu -> setCurrentWidget ( getKeyPic ) ; label -> setText ( tr("Pick key picture for decryption") ) ; Alert ( Error ) ; /////////////////////////////////////////////////////////////////// picTool -> deleteLater ( ) ; vcf -> deleteLater ( ) ; /////////////////////////////////////////////////////////////////// picTool = NULL ; vcf = NULL ; } void N::PaintingSecretGui::ViewDepot(void) { QString path ; PickPicture * pp = (PickPicture *)BackWidget ; if (!pp->CurrentPath(path)) return ; QString file = pp->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; picTool = new PaintingViewTool ( menu , plan ) ; vcf = new VcfView ( stack , plan ) ; menu -> addWidget ( picTool ) ; stack -> addWidget ( vcf ) ; menu -> setCurrentWidget ( picTool ) ; stack -> setCurrentWidget ( vcf ) ; header -> setCurrentWidget ( label ) ; plan -> processEvents ( ) ; vcf -> ViewPicture ( IFG , NULL ) ; vcf -> resize ( stack->size() ) ; Alert ( Done ) ; //////////////////////////////////////////////////////////// vcf -> skipMouse = true ; nConnect ( picTool , SIGNAL(Back ()) , this , SLOT (ReturnDepot()) ) ; nConnect ( picTool , SIGNAL(ZoomIn ()) , vcf , SLOT (ZoomIn ()) ) ; nConnect ( picTool , SIGNAL(ZoomOut ()) , vcf , SLOT (ZoomOut ()) ) ; } void N::PaintingSecretGui::ReturnDepot(void) { header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( BackWidget ) ; menu -> setCurrentWidget ( BackMenu ) ; label -> setText ( ReturnLabel ) ; Alert ( Error ) ; ////////////////////////////////////////////// picTool -> deleteLater ( ) ; vcf -> deleteLater ( ) ; ////////////////////////////////////////////// picTool = NULL ; vcf = NULL ; } void N::PaintingSecretGui::ObtainPic(void) { QString path ; if (!pickPicture->CurrentPath(path)) return ; QString file = pickPicture->Root.absoluteFilePath ( path ) ; ////////////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; ////////////////////////////////////////////////////////////////// header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( encryptReport ) ; menu -> setCurrentWidget ( encrypt ) ; label -> setText ( tr("Encrypt data into a picture") ) ; ////////////////////////////////////////////////////////////////// SourcePicture = file ; } void N::PaintingSecretGui::ObtainKey(void) { QString path ; if (!pickPicture->CurrentPath(path)) return ; QString file = pickPicture->Root.absoluteFilePath ( path ) ; ////////////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; ////////////////////////////////////////////////////////////////// header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( encryptReport ) ; menu -> setCurrentWidget ( encrypt ) ; label -> setText ( tr("Encrypt data into a picture") ) ; ////////////////////////////////////////////////////////////////// KeyPicture = file ; } void N::PaintingSecretGui::ObtainEncrypted(void) { QString path ; if (!pickEncrypt->CurrentPath(path)) return ; QString file = pickEncrypt->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; //////////////////////////////////////////////////////////////// header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( decryptReport ) ; menu -> setCurrentWidget ( decrypt ) ; label -> setText ( tr("Decrypt data from picture") ) ; //////////////////////////////////////////////////////////////// DecryptPicture = file ; } void N::PaintingSecretGui::ObtainKeys(void) { QString path ; if (!pickKey->CurrentPath(path)) return ; QString file = pickKey->Root.absoluteFilePath ( path ) ; //////////////////////////////////////////////////////////////// QFileInfo IFG(file) ; if (!IFG.exists()) return ; //////////////////////////////////////////////////////////////// header -> setCurrentWidget ( label ) ; stack -> setCurrentWidget ( decryptReport ) ; menu -> setCurrentWidget ( decrypt ) ; label -> setText ( tr("Decrypt data from picture") ) ; //////////////////////////////////////////////////////////////// DecryptKey = file ; } void N::PaintingSecretGui::FileRename(void) { header -> setCurrentWidget ( lineRename ) ; QTreeWidgetItem * item = pickArchive->currentItem ( ) ; if (NotNull(item)) { QString path = item -> text ( 0 ) ; QDir cp = pickArchive -> CurrentPath ( ) ; QDir rp = pickArchive -> Path ( ) ; path = cp . absoluteFilePath ( path ) ; path = rp . relativeFilePath ( path ) ; lineRename -> blockSignals ( true ) ; lineRename -> setText ( path ) ; lineRename -> blockSignals ( false ) ; } else { lineRename -> blockSignals ( true ) ; lineRename -> setText ( "" ) ; lineRename -> blockSignals ( false ) ; } ; lineRename -> setFocus ( Qt::TabFocusReason ) ; } void N::PaintingSecretGui::RenameAction(void) { QTreeWidgetItem * item = pickArchive->currentItem ( ) ; if (NotNull(item)) { QString name = lineRename->text() ; QString path = item -> text ( 0 ) ; QDir cp = pickArchive -> CurrentPath ( ) ; QDir rp = pickArchive -> Path ( ) ; path = cp . absoluteFilePath ( path ) ; if (name.length()>0) { name = rp . absoluteFilePath ( name ) ; if (name.length()>0 && path.length()) { QFile :: rename ( path , name ) ; } ; } ; } ; header -> setCurrentWidget ( folderList ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; Alert ( Error ) ; } void N::PaintingSecretGui::FileMove(void) { header -> setCurrentWidget ( lineMove ) ; QTreeWidgetItem * item = pickArchive->currentItem ( ) ; if (NotNull(item)) { QString path = item -> text ( 0 ) ; QDir cp = pickArchive -> CurrentPath ( ) ; QDir rp = pickArchive -> Path ( ) ; path = cp . absoluteFilePath ( path ) ; path = rp . relativeFilePath ( path ) ; lineMove -> blockSignals ( true ) ; lineMove -> setText ( path ) ; lineMove -> blockSignals ( false ) ; } else { lineMove -> blockSignals ( true ) ; lineMove -> setText ( "" ) ; lineMove -> blockSignals ( false ) ; } ; lineMove -> setFocus ( Qt::TabFocusReason ) ; } void N::PaintingSecretGui::MoveAction(void) { QTreeWidgetItem * item = pickArchive->currentItem ( ) ; if (NotNull(item)) { QString name = lineMove->text() ; QString path = item -> text ( 0 ) ; QDir cp = pickArchive -> CurrentPath ( ) ; QDir rp = pickArchive -> Path ( ) ; path = cp . absoluteFilePath ( path ) ; if (name.length()>0) { name = rp . absoluteFilePath ( name ) ; if (name.length()>0 && path.length()) { QFile :: rename ( path , name ) ; } ; } ; } ; header -> setCurrentWidget ( folderList ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; Alert ( Error ) ; } void N::PaintingSecretGui::FileDirectory(void) { header -> setCurrentWidget ( lineDirectory ) ; lineDirectory -> blockSignals ( true ) ; lineDirectory -> setText ( "" ) ; lineDirectory -> blockSignals ( false ) ; lineDirectory -> setFocus ( Qt::TabFocusReason ) ; } void N::PaintingSecretGui::DirectoryAction(void) { QString name = lineDirectory -> text ( ) ; if (name.length()>0) { QDir cp = pickArchive -> CurrentPath ( ) ; QDir rp = pickArchive -> Path ( ) ; QString path = cp . absoluteFilePath ( name ) ; QString tp = rp . absoluteFilePath ( "" ) ; if (path.contains(tp)) { cp . mkdir ( name ) ; } ; } ; header -> setCurrentWidget ( folderList ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; Alert ( Error ) ; } void N::PaintingSecretGui::FolderBack(void) { header -> setCurrentWidget ( folderList ) ; } void N::PaintingSecretGui::EditText(void) { QTreeWidgetItem * item = pickArchive->currentItem ( ) ; if (IsNull(item)) return ; QDir cp = pickArchive -> CurrentPath ( ) ; QString path = item -> text ( 0 ) ; path = cp . absoluteFilePath ( path ) ; QFileInfo F ( path ) ; QString S = F.suffix () ; S = S.toLower() ; if ( S != "txt" ) return ; emit LoadText ( pickArchive->Path() , pickArchive -> CurrentPath() , path ) ; #ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX //////////////////////////////////////////////////////////// plainText -> clear ( ) ; header -> setCurrentWidget ( line ) ; stack -> setCurrentWidget ( plainText ) ; menu -> setCurrentWidget ( textEdit ) ; label -> setText ( tr("Plain text editor" ) ) ; //////////////////////////////////////////////////////////// QByteArray Body ; File :: toByteArray ( path , Body ) ; plainText -> blockSignals ( true ) ; plainText -> append ( QString::fromUtf8(Body) ) ; plainText -> verticalScrollBar ( ) -> setValue ( 0 ) ; plainText -> blockSignals ( false ) ; //////////////////////////////////////////////////////////// line -> blockSignals ( true ) ; line -> setText ( item -> text ( 0 ) ) ; line -> blockSignals ( false ) ; //////////////////////////////////////////////////////////// Alert ( Error ) ; #endif } void N::PaintingSecretGui::BackEdit(void) { header -> setCurrentWidget ( folderList ) ; stack -> setCurrentWidget ( pickArchive ) ; menu -> setCurrentWidget ( folderEdit ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; Alert ( Click ) ; } void N::PaintingSecretGui::NewEdit(void) { plainText -> clear ( ) ; } void N::PaintingSecretGui::SaveEdit(void) { QString note = line->text() ; if (note.length()<=0) return ; QDir r = pickArchive -> Path( ) ; QString file = r.absoluteFilePath ( note ) ; QString head = r.absoluteFilePath ( "" ) ; if (!file.contains(head)) return ; QString text = plainText -> toPlainText ( ) ; QByteArray body = text . toUtf8 ( ) ; QFileInfo fdir ( file ) ; r . mkpath ( fdir . absolutePath ( ) ) ; File :: toFile ( file , body ) ; ///////////////////////////////////////////////// header -> setCurrentWidget ( folderList ) ; stack -> setCurrentWidget ( pickArchive ) ; menu -> setCurrentWidget ( folderEdit ) ; plan -> processEvents ( ) ; pickArchive -> List ( ) ; Alert ( Click ) ; } void N::PaintingSecretGui::FileFtp(void) { QString path = pickArchive->CurrentPath().absoluteFilePath("") ; emit Transfer ( path ) ; } void N::PaintingSecretGui::ImportPicture(void) { QString path = pickPicture->Root.absoluteFilePath("") ; emit Obtain ( path ) ; } void N::PaintingSecretGui::ImportKey(void) { QString path = pickPicture->Root.absoluteFilePath("") ; emit Obtain ( path ) ; } void N::PaintingSecretGui::ImportEncrypted(void) { QString path = pickEncrypt->Root.absoluteFilePath("") ; emit Transfer ( path ) ; } void N::PaintingSecretGui::ImportKeys(void) { QString path = pickKey->Root.absoluteFilePath("") ; emit Transfer ( path ) ; }
53.919092
119
0.332223
Vladimir-Lin
6edb231d511296e3cc3f04fab65844934e4425b2
3,697
cc
C++
src/page.cc
minkezhang/giga
bae6fe295e417b132ba5b6064fb25906188e3cbe
[ "MIT" ]
1
2016-11-23T14:55:29.000Z
2016-11-23T14:55:29.000Z
src/page.cc
cripplet/giga
bae6fe295e417b132ba5b6064fb25906188e3cbe
[ "MIT" ]
null
null
null
src/page.cc
cripplet/giga
bae6fe295e417b132ba5b6064fb25906188e3cbe
[ "MIT" ]
1
2021-12-24T23:08:00.000Z
2021-12-24T23:08:00.000Z
#include <random> #include <sstream> #include <string> #include <vector> #include "libs/cachepp/globals.h" #include "libs/exceptionpp/exception.h" #include "libs/md5/md5.h" #include "src/page.h" giga::Page::Page(cachepp::identifier id, std::string filename, size_t file_offset, size_t size, bool is_dirty) : cachepp::LineInterface<std::string>::LineInterface(id), filename(filename), file_offset(file_offset), size(size) { this->is_dirty = is_dirty; this->set_filename(this->filename); this->data.clear(); this->set_checksum(this->hash()); this->r = rand(); } giga::Page::~Page() { // remove tmp file to lessen bloat if(this->cached.compare(this->filename) != 0 && this->filename.compare("") != 0) { remove(this->get_filename().c_str()); } } size_t giga::Page::get_size() { return(this->size); } void giga::Page::set_size(size_t size) { this->size = size; } size_t giga::Page::probe(size_t offset, size_t len, bool is_forward) { if(offset > this->get_size()) { throw(exceptionpp::InvalidOperation("giga::Page::probe", "offset is invalid")); } if(is_forward) { return((this->get_size() - offset) > len ? len : (this->get_size() - offset)); } else { return(offset > len ? len : offset); } } void giga::Page::set_filename(std::string filename) { this->cached = filename; } std::string giga::Page::get_filename() { if(this->get_is_dirty()) { std::stringstream path; std::stringstream buf; buf << this->cached << "_" << this->get_identifier(); path << "/tmp/giga/" << md5(buf.str()) << this->r; return(path.str()); } else { return(this->cached); } } void giga::Page::set_file_offset(size_t file_offset) { this->file_offset = file_offset; } void giga::Page::aux_load() { // deallocate the data vector this->data.clear(); std::vector<uint8_t>().swap(this->data); if(this->get_size() == 0) { return; } std::vector<uint8_t> buf(this->get_size(), 0); // load data into the page if(!this->get_is_dirty()) { FILE *fp = fopen(this->get_filename().c_str(), "r"); if(fp == NULL) { std::stringstream buf; buf << "cannot open working file '" << this->get_filename() << "'"; throw(exceptionpp::RuntimeError("giga::Page::aux_load", buf.str())); } if(fseek(fp, this->file_offset, SEEK_SET) == -1) { fclose(fp); fp = NULL; throw(exceptionpp::RuntimeError("giga::Page::aux_load", "invalid result returned from fseek")); } if(fread(buf.data(), sizeof(char), this->get_size(), fp) < this->get_size()) { fclose(fp); fp = NULL; throw(exceptionpp::RuntimeError("giga::Page::aux_load", "invalid result returned from fread")); } fclose(fp); fp = NULL; buf.swap(this->data); } } void giga::Page::aux_unload() { this->set_size(this->data.size()); if(this->get_is_dirty()) { FILE *fp = fopen(this->get_filename().c_str(), "w"); if(fp == NULL) { std::stringstream buf; buf << "cannot open working file '" << this->get_filename() << "'"; throw(exceptionpp::RuntimeError("giga::Page::aux_unload", buf.str())); } if(fputs(std::string(this->data.begin(), this->data.end()).c_str(), fp) < 0) { fclose(fp); fp = NULL; throw(exceptionpp::RuntimeError("giga::Page::aux_unload", "invalid result returned from fputs")); } fclose(fp); fp = NULL; // we are now reading a "clean" file again next time this->set_file_offset(0); // remove tmp file to lessen bloat if(this->cached.compare(this->filename)) { remove(this->cached.c_str()); } this->set_filename(this->get_filename()); this->set_is_dirty(false); } this->data.clear(); std::vector<uint8_t>().swap(this->data); } std::string giga::Page::hash() { return(md5(std::string(this->data.begin(), this->data.end()))); }
28.007576
227
0.650798
minkezhang
6edcd5c4f6463bf25aca47ed69148505c77bd844
292
cpp
C++
11172-Relational_Operators/RO.cpp
dangercard/Uva_Challenges
735bf80da5d1995fece4614d38174d1ea276e7c2
[ "Apache-2.0" ]
null
null
null
11172-Relational_Operators/RO.cpp
dangercard/Uva_Challenges
735bf80da5d1995fece4614d38174d1ea276e7c2
[ "Apache-2.0" ]
null
null
null
11172-Relational_Operators/RO.cpp
dangercard/Uva_Challenges
735bf80da5d1995fece4614d38174d1ea276e7c2
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std ; int main() { int n,a,b ; cin >> n ; while(n--) { cin >> a >> b ; if(a > b) { cout << ">" << endl ; } else if(b > a) { cout << "<" << endl ; } else { cout << "=" << endl ; } } }
10.068966
27
0.342466
dangercard
6ee1d7a9db4930b9f902cd0fba265dd5e38d3983
1,445
hpp
C++
addons/UH60/config/turrets/pilotCamera.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
14
2021-02-11T23:23:21.000Z
2021-09-08T05:36:47.000Z
addons/UH60/config/turrets/pilotCamera.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
130
2021-09-09T21:43:16.000Z
2022-03-30T09:00:37.000Z
addons/UH60/config/turrets/pilotCamera.hpp
ZHANGTIANYAO1/H-60
4c6764f74190dbe7d81ddeae746cf78d8b7dff92
[ "Naumen", "Condor-1.1", "MS-PL" ]
11
2021-02-18T19:55:51.000Z
2021-09-01T17:08:47.000Z
class OpticsIn { class Wide { opticsDisplayName = "TRK COR"; initAngleX = 0; minAngleX = -360; maxAngleX = 360; initAngleY = 0; minAngleY = -15; maxAngleY = 85; initFov = 0.3; minFov = 0.3; maxFov = 0.3; visionMode[] = {"Normal", "NVG", "Ti"}; thermalMode[] = {0, 1}; directionStabilized = 1; horizontallyStabilized = 1; gunnerOpticsModel = "\A3\Weapons_F\empty"; opticsPPEffects[] = {"OpticsCHAbera3","OpticsBlur3"}; gunnerOpticsEffect[] = {"TankCommanderOptics2"}; }; class WideT: Wide { initFov = 0.2; minFov = 0.2; maxFov = 0.2; gunnerOpticsModel = "\A3\Weapons_F\empty"; }; class MediumT: WideT { initFov = 0.1; minFov = 0.1; maxFov = 0.1; gunnerOpticsModel = "\A3\Weapons_F\empty"; }; class NarrowT: WideT { initFov = 0.022; minFov = 0.022; maxFov = 0.022; gunnerOpticsModel = "\A3\Weapons_F\empty"; }; class NarrowT2: WideT { initFov = 0.0092; minFov = 0.0092; maxFov = 0.0092; gunnerOpticsModel = "\A3\Weapons_F\empty"; }; }; stabilizedInAxes = 3; minElev = -40; maxElev = 90; initElev = 0; minTurn = -180; maxTurn = 180; initTurn = 0; maxXRotSpeed=0.5; maxYRotSpeed=0.5; pilotOpticsShowCursor=1; controllable=1;
22.936508
61
0.536332
ZHANGTIANYAO1
6ee36251eab69097dfc764dd240c98d10b042426
145
hpp
C++
src/Game.hpp
eXpl0it3r/MartisOpibus
120910e564f73a8a2ed4822d0a1daf2cb9a15a2f
[ "CC0-1.0" ]
null
null
null
src/Game.hpp
eXpl0it3r/MartisOpibus
120910e564f73a8a2ed4822d0a1daf2cb9a15a2f
[ "CC0-1.0" ]
null
null
null
src/Game.hpp
eXpl0it3r/MartisOpibus
120910e564f73a8a2ed4822d0a1daf2cb9a15a2f
[ "CC0-1.0" ]
null
null
null
#pragma once #include <SFML/Graphics/RenderWindow.hpp> class Game { public: void Run(); private: sf::RenderWindow m_window; };
11.153846
42
0.655172
eXpl0it3r
6eeb77bb351b602838edfcf2dbb32cf286f9c8ba
1,285
cpp
C++
Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp
yokeshrana/Fast_Algorithms_in_Data_Structures
2346fee16c6c3ffceac7cb79b1f449b4d8dc9df2
[ "MIT" ]
4
2021-01-15T16:30:48.000Z
2021-08-12T03:17:00.000Z
Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
null
null
null
Treap (Cartesian Tree)/Cartesian Tree Build (stack).cpp
andy489/Fast_Algorithms_in_Data_Structures
0f28a75030df3367902f0aa859a34096ea2b2582
[ "MIT" ]
2
2021-02-24T14:50:08.000Z
2021-02-28T17:39:41.000Z
// github.com/andy489 #include <vector> #include <stack> using namespace std; vector<int> build(int *A, int n) { vector<int> parent(n, -1); stack<int> s; for (int i = 0; i < n; ++i) { int last = -1; while (!s.empty() && A[s.top()] >= A[i]) { last = s.top(); s.pop(); } if (!s.empty()) parent[i] = s.top(); if (last >= 0) parent[last] = i; s.push(i); } return parent; } #include <queue> void display(int u, vector<vector<int>> &adj) { queue<int> Q; Q.push(u); int SZ; while (!Q.empty()) { SZ = Q.size(); while (SZ--) { int cur = Q.front(); Q.pop(); printf("%d ", cur); for (const int &child: adj[cur]) Q.push(child); } printf("\n"); } } int main() { int A[] = {7, 3, 500, 12, 1001, 10, 17, 128}; int n = sizeof A / sizeof(int); vector<int> CartesianTree = build(A, n); vector<vector<int>> adj(n, vector<int>()); int root = -1; for (int i = 0; i < n; ++i) { if (CartesianTree[i] != -1) adj[CartesianTree[i]].push_back(i); else root = i; } return display(root, adj), 0; }
19.769231
50
0.438911
yokeshrana
6ef56e394fd47f690e8ca8dc51d23f417aa34b7f
2,023
cpp
C++
src/KeyboardHook.cpp
Erwan28250/KeyChattering
b69e0b25064232b6bea9a87d6b9070a5dd04d40e
[ "MIT" ]
1
2021-12-18T01:47:28.000Z
2021-12-18T01:47:28.000Z
src/KeyboardHook.cpp
Erwan28250/KeyChattering
b69e0b25064232b6bea9a87d6b9070a5dd04d40e
[ "MIT" ]
null
null
null
src/KeyboardHook.cpp
Erwan28250/KeyChattering
b69e0b25064232b6bea9a87d6b9070a5dd04d40e
[ "MIT" ]
null
null
null
/* * MIT Licence * * KeyChattering * * Copyright © 2021 Erwan Saclier de la Bâtie (Erwan28250) * * 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 "KeyboardHook.h" #include "KeyPressData.h" #include <iostream> LRESULT CALLBACK keyHookProc( int nCode, WPARAM wParam, LPARAM lParam) { if (nCode < 0) return CallNextHookEx(nullptr, nCode, wParam, lParam); switch (wParam) { case WM_KEYDOWN: case WM_SYSKEYDOWN: { PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam; bool result = KeyPressData::instance()->isKeyPressChatter(p->vkCode); if (result) return 1; } break; case WM_KEYUP: case WM_SYSKEYUP: { PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam; bool result = KeyPressData::instance()->isKeyReleaseChatter(p->vkCode); if (result) return 1; } break; } return CallNextHookEx(nullptr, nCode, wParam, lParam); }
38.169811
160
0.692042
Erwan28250
6ef75b61101c57ae2bd1673bc48a238ded03d753
710
cpp
C++
p/3k/3741/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/3k/3741/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
p/3k/3741/main.cpp
josedelinux/luogu
f9ce86b8623224512aa3f9e1eecc45d3c89c74e4
[ "MIT" ]
null
null
null
/* 4 possibilities: vv(ok) kk(ok) vk(ok,target) kv(unchangeable) */ #include <bits/stdc++.h> #define DEBUGn using namespace std; int main() { int cnt = 0; int flag = 0; // "yes we can change" flag int n; string s; cin >> n; cin >> s; for (int i = 0; i < n - 1; i++) { int cur = s[i]; int next = s[i + 1]; if (cur == 'V' && next == 'K') { cnt++; // disable them s[i] = tolower(cur); s[i + 1] = tolower(next); } } for (int i = 0; i < n - 1; i++) { int cur = s[i]; int next = s[i + 1]; if (!islower(s[i]) && cur == next) flag = 1; } #ifdef DEBUG cout << "flag: " << flag << endl; #endif cout << cnt + flag << endl; return 0; }
15.434783
48
0.474648
josedelinux
6ef7a80f4b765a75be37b615c05d2b080fe32d77
7,821
hh
C++
include/stmicro/stm32l4x6/syscfg.hh
no111u3/lp_devices
9fcd370a2b8a3f03a8a2181e403ffe562e48a611
[ "Apache-2.0" ]
null
null
null
include/stmicro/stm32l4x6/syscfg.hh
no111u3/lp_devices
9fcd370a2b8a3f03a8a2181e403ffe562e48a611
[ "Apache-2.0" ]
null
null
null
include/stmicro/stm32l4x6/syscfg.hh
no111u3/lp_devices
9fcd370a2b8a3f03a8a2181e403ffe562e48a611
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Boris Vinogradov <[email protected]> * * 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. * * Hardware support for syscfg * @file syscfg.hh * @author Boris Vinogradov */ #include <associate_bit.hh> #include <io_register.hh> #include <types.hh> #ifndef SYSCFG_HH #define SYSCFG_HH /* System configuration controller */ template <lp::addr_t base_address> struct syscfg_t { /* memory remap register */ using memrmp = lp::io_register<lp::u32_t, base_address + 0x0>; /* Flash Bank mode selection */ using memrmp_fb_mode = lp::assoc_bit<memrmp, 8>; /* QUADSPI memory mapping swap */ using memrmp_qfs = lp::assoc_bit<memrmp, 3>; /* Memory mapping selection */ using memrmp_mem_mode = lp::assoc_bit<memrmp, 0, 3>; /* configuration register 1 */ using cfgr1 = lp::io_register<lp::u32_t, base_address + 0x4>; /* Floating Point Unit interrupts enable bits */ using cfgr1_fpu_ie = lp::assoc_bit<cfgr1, 26, 6>; /* I2C3 Fast-mode Plus driving capability activation */ using cfgr1_i2c3_fmp = lp::assoc_bit<cfgr1, 22>; /* I2C2 Fast-mode Plus driving capability activation */ using cfgr1_i2c2_fmp = lp::assoc_bit<cfgr1, 21>; /* I2C1 Fast-mode Plus driving capability activation */ using cfgr1_i2c1_fmp = lp::assoc_bit<cfgr1, 20>; /* Fast-mode Plus (Fm+) driving capability activation on PB9 */ using cfgr1_i2c_pb9_fmp = lp::assoc_bit<cfgr1, 19>; /* Fast-mode Plus (Fm+) driving capability activation on PB8 */ using cfgr1_i2c_pb8_fmp = lp::assoc_bit<cfgr1, 18>; /* Fast-mode Plus (Fm+) driving capability activation on PB7 */ using cfgr1_i2c_pb7_fmp = lp::assoc_bit<cfgr1, 17>; /* Fast-mode Plus (Fm+) driving capability activation on PB6 */ using cfgr1_i2c_pb6_fmp = lp::assoc_bit<cfgr1, 16>; /* I/O analog switch voltage booster enable */ using cfgr1_boosten = lp::assoc_bit<cfgr1, 8>; /* Firewall disable */ using cfgr1_fwdis = lp::assoc_bit<cfgr1, 0>; /* external interrupt configuration register 1 */ using exticr1 = lp::io_register<lp::u32_t, base_address + 0x8>; /* EXTI 3 configuration bits */ using exticr1_exti3 = lp::assoc_bit<exticr1, 12, 3>; /* EXTI 2 configuration bits */ using exticr1_exti2 = lp::assoc_bit<exticr1, 8, 3>; /* EXTI 1 configuration bits */ using exticr1_exti1 = lp::assoc_bit<exticr1, 4, 3>; /* EXTI 0 configuration bits */ using exticr1_exti0 = lp::assoc_bit<exticr1, 0, 3>; /* external interrupt configuration register 2 */ using exticr2 = lp::io_register<lp::u32_t, base_address + 0xc>; /* EXTI 7 configuration bits */ using exticr2_exti7 = lp::assoc_bit<exticr2, 12, 3>; /* EXTI 6 configuration bits */ using exticr2_exti6 = lp::assoc_bit<exticr2, 8, 3>; /* EXTI 5 configuration bits */ using exticr2_exti5 = lp::assoc_bit<exticr2, 4, 3>; /* EXTI 4 configuration bits */ using exticr2_exti4 = lp::assoc_bit<exticr2, 0, 3>; /* external interrupt configuration register 3 */ using exticr3 = lp::io_register<lp::u32_t, base_address + 0x10>; /* EXTI 11 configuration bits */ using exticr3_exti11 = lp::assoc_bit<exticr3, 12, 3>; /* EXTI 10 configuration bits */ using exticr3_exti10 = lp::assoc_bit<exticr3, 8, 3>; /* EXTI 9 configuration bits */ using exticr3_exti9 = lp::assoc_bit<exticr3, 4, 3>; /* EXTI 8 configuration bits */ using exticr3_exti8 = lp::assoc_bit<exticr3, 0, 3>; /* external interrupt configuration register 4 */ using exticr4 = lp::io_register<lp::u32_t, base_address + 0x14>; /* EXTI15 configuration bits */ using exticr4_exti15 = lp::assoc_bit<exticr4, 12, 3>; /* EXTI14 configuration bits */ using exticr4_exti14 = lp::assoc_bit<exticr4, 8, 3>; /* EXTI13 configuration bits */ using exticr4_exti13 = lp::assoc_bit<exticr4, 4, 3>; /* EXTI12 configuration bits */ using exticr4_exti12 = lp::assoc_bit<exticr4, 0, 3>; /* SCSR */ using scsr = lp::io_register<lp::u32_t, base_address + 0x18>; /* SRAM2 busy by erase operation */ using scsr_sram2bsy = lp::assoc_bit<scsr, 1>; /* SRAM2 Erase */ using scsr_sram2er = lp::assoc_bit<scsr, 0>; /* CFGR2 */ using cfgr2 = lp::io_register<lp::u32_t, base_address + 0x1c>; /* SRAM2 parity error flag */ using cfgr2_spf = lp::assoc_bit<cfgr2, 8>; /* ECC Lock */ using cfgr2_eccl = lp::assoc_bit<cfgr2, 3>; /* PVD lock enable bit */ using cfgr2_pvdl = lp::assoc_bit<cfgr2, 2>; /* SRAM2 parity lock bit */ using cfgr2_spl = lp::assoc_bit<cfgr2, 1>; /* Cortex-M4 LOCKUP (Hardfault) output enable bit */ using cfgr2_cll = lp::assoc_bit<cfgr2, 0>; /* SWPR */ using swpr = lp::io_register<lp::u32_t, base_address + 0x20>; /* SRAM2 page 31 write protection */ using swpr_p31wp = lp::assoc_bit<swpr, 31>; /* P30WP */ using swpr_p30wp = lp::assoc_bit<swpr, 30>; /* P29WP */ using swpr_p29wp = lp::assoc_bit<swpr, 29>; /* P28WP */ using swpr_p28wp = lp::assoc_bit<swpr, 28>; /* P27WP */ using swpr_p27wp = lp::assoc_bit<swpr, 27>; /* P26WP */ using swpr_p26wp = lp::assoc_bit<swpr, 26>; /* P25WP */ using swpr_p25wp = lp::assoc_bit<swpr, 25>; /* P24WP */ using swpr_p24wp = lp::assoc_bit<swpr, 24>; /* P23WP */ using swpr_p23wp = lp::assoc_bit<swpr, 23>; /* P22WP */ using swpr_p22wp = lp::assoc_bit<swpr, 22>; /* P21WP */ using swpr_p21wp = lp::assoc_bit<swpr, 21>; /* P20WP */ using swpr_p20wp = lp::assoc_bit<swpr, 20>; /* P19WP */ using swpr_p19wp = lp::assoc_bit<swpr, 19>; /* P18WP */ using swpr_p18wp = lp::assoc_bit<swpr, 18>; /* P17WP */ using swpr_p17wp = lp::assoc_bit<swpr, 17>; /* P16WP */ using swpr_p16wp = lp::assoc_bit<swpr, 16>; /* P15WP */ using swpr_p15wp = lp::assoc_bit<swpr, 15>; /* P14WP */ using swpr_p14wp = lp::assoc_bit<swpr, 14>; /* P13WP */ using swpr_p13wp = lp::assoc_bit<swpr, 13>; /* P12WP */ using swpr_p12wp = lp::assoc_bit<swpr, 12>; /* P11WP */ using swpr_p11wp = lp::assoc_bit<swpr, 11>; /* P10WP */ using swpr_p10wp = lp::assoc_bit<swpr, 10>; /* P9WP */ using swpr_p9wp = lp::assoc_bit<swpr, 9>; /* P8WP */ using swpr_p8wp = lp::assoc_bit<swpr, 8>; /* P7WP */ using swpr_p7wp = lp::assoc_bit<swpr, 7>; /* P6WP */ using swpr_p6wp = lp::assoc_bit<swpr, 6>; /* P5WP */ using swpr_p5wp = lp::assoc_bit<swpr, 5>; /* P4WP */ using swpr_p4wp = lp::assoc_bit<swpr, 4>; /* P3WP */ using swpr_p3wp = lp::assoc_bit<swpr, 3>; /* P2WP */ using swpr_p2wp = lp::assoc_bit<swpr, 2>; /* P1WP */ using swpr_p1wp = lp::assoc_bit<swpr, 1>; /* P0WP */ using swpr_p0wp = lp::assoc_bit<swpr, 0>; /* SKR */ using skr = lp::io_register<lp::u32_t, base_address + 0x24>; /* SRAM2 write protection key for software erase */ using skr_key = lp::assoc_bit<skr, 0, 8>; }; using syscfg = syscfg_t<0x40010000>; #endif // SYSCFG_HH
36.71831
81
0.628692
no111u3